0% found this document useful (0 votes)
45 views

module1_C++

This document serves as an introduction to C++ programming, covering its history, key features, and basic syntax. It explains object-oriented programming concepts such as classes, objects, inheritance, encapsulation, and polymorphism. Additionally, it provides a simple example of a C++ program and discusses the benefits and limitations of the language.

Uploaded by

pallavi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
45 views

module1_C++

This document serves as an introduction to C++ programming, covering its history, key features, and basic syntax. It explains object-oriented programming concepts such as classes, objects, inheritance, encapsulation, and polymorphism. Additionally, it provides a simple example of a C++ program and discusses the benefits and limitations of the language.

Uploaded by

pallavi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 26

Introduction to C++ Programming BPLCK205D

Module-1
Introduction to Object Oriented Programming: Computer programming background- C++ overview.
First C++ Program -Basic C++ syntax,
Object Oriented Programming: What is an object, Classes, methods and messages, abstraction and
encapsulation, inheritance, abstract classes, polymorphism.
INTRODUCTION TO OBJECT ORIENTED PROGRAMMING
1.1 Computer programming background
The C++ programming language has a history going back to 1979, when Bjarne Stroustrup was doing
work for his Ph.D. thesis. He began work on "C with Classes", which as the name implies was meant to
be a superset of the C language. His goal was to add object-oriented programming into the C language,
which was and still is a language well-respected for its portability without sacrificing speed or low-level
functionality.
His language included classes, basic inheritance, inlining, default function arguments, and strong type
checking in addition to all the features of the C language. The first C with Classes compiler was called
Cfront, which was derived from a C compiler called CPre. It was a program designed to translate C with
Classes code to ordinary C
In 1983, the name of the language was changed from C with Classes to C++. The ++ operator in the C
language is an operator for incrementing a variable, which gives some insight into how Stroustrup regarded
the language. Many new features were added around this time, the most notable of which are virtual
functions, function overloading, references with the & symbol, the const keyword, and single-line comments
using two forward slashes.
In 1985, C++ was implemented as a commercial product. The language was not officially standardized
yet. The language was updated again in 1989 to include protected and static members, as well as an
inheritance from several classes.
In 1990, Turbo C++ was released as a commercial product. Turbo C++ added a lot of additional libraries
which have had a considerable impact on C++'s development.
In 1998, the C++ standards committee published the first international standard for C++ ISO/IEC
14882:1998, which is informally known as C++98. The Standard Template Library, which began its
conceptual development in 1979, was also included.
In 2003, the committee responded to multiple problems that were reported with their 1998 standard and
revised it accordingly. The changed language was named C++03
In mid-2011, the new C++ standard (C++11) was finished. The new features included Regex support, a
randomization library, a new C++ time library, atomics support, a standard threading library, a new for loop
syntax providing functionality similar to for each loops in certain other languages, the auto keyword, new
container classes, better support for unions and array-initialization lists and variadic templates.

Pallavi C S Assistant Prof. Dept. of Data Science AIT, Chikkamagaluru Page 1


Introduction to C++ Programming BPLCK205D
1.2 C++ overview
 C++ is a statically typed, compiled, general-purpose, case-sensitive, free-form programming
language that supports procedural, object-oriented, and generic programming.
 C++ is regarded as a middle-level language, as it comprises a combination of both high-level and
low-level language features.
 C++ was developed by Bjarne Stroustrup starting in 1979 at Bell Labs in Murray Hill, New Jersey, as
an enhancement to the C language and originally named C with Classes but later it was renamed C++
in 1983
 C++ is a superset of C, and that virtually any legal C program is a legal C++ program.
Features of C++
It provides a lot of features that are given below.
 Classes
 Objects
 Inheritance
 Encapsulation
 Abstraction
 Polymorphism
 Method Overriding
 Method Overloading
 Constructor and Destructor
Use of C++/Benefits of C++:
 C++ is used by hundreds of thousands of programmers in essentially every application domain.
 C++ is being highly used to write device drivers and other software that rely on direct manipulation
of hardware under real-time constraints.
 C++ is widely used for teaching and research because it is clean enough for successful teaching of
basic concepts. Anyone who has used either an Apple Macintosh or a PC running Windows has
indirectly used C++ because the primary user interfaces of these systems are written in C++
 Modularity for easier troubleshooting.
 Reuse of code through inheritance
 Flexibility through polymorphism
 Effective problem solving
Limitations of C:
 Lack of Global View: Programmers realized the limitations of C only when the C programs were
used on a very large scale. It became very difficult for the programmers to remember every part of
the program. This is a problem partly with the design and partly due to the inability of the language

Pallavi C S Assistant Prof. Dept. of Data Science AIT, Chikkamagaluru Page 2


Introduction to C++ Programming BPLCK205D
to express a lengthy program as an abstraction of smaller individual units. Over the years,
programmers realized this and found ways to avoid this problem. One such commonly practiced
method is to make the program modular, that is, to divide the program into smaller segments and
implement these segments by different functions
 Not Designed for Reusability: There is another problem with the style of programming in C. We
need many building blocks for a large program. For example, a large payroll program would require
all the information about each employee. Management of employee information is one building
block for the payroll program. A human resource management program also requires the employee
information. Both sets of information may not be exactly the same, though both of them need to be
consistent. It would be a better approach to share the information as much as possible between all
those who need it, and provide additional information only in special cases.
1.3 First C++ Program
#include <iostream>
using namespace std;
// main ( ) is where program execution begins.
int main ( )
{
cout << " This is my first C++ program "; // prints This is my first C++
return 0;
}

Let us look at the various parts of the above program:


 The C++ language defines several headers, which contain information that is either necessary or
useful to your program. For this program, the header <iostream> is needed.
 The line using namespace std; tells the compiler to use the std namespace. Namespaces are a
relatively recent addition to C++.
 The next line ‘// main() is where program execution begins.’ is a single-line comment available in C+
+. Single-line comments begin with // and stop at the end of the line.
 The line int main ( ) is the main function where program execution begins.
 The next line cout << "This is my first C++ program"; causes the message "This is my first C++
program" to be displayed on the screen.
 The next line returns 0; terminates main () function and causes it to return the value 0 to the calling
process.

1.4 Basic C++ syntax

Pallavi C S Assistant Prof. Dept. of Data Science AIT, Chikkamagaluru Page 3


Introduction to C++ Programming BPLCK205D
When we consider a C++ program, it can be defined as a collection of objects that communicate via
invoking each other's methods. Let us now briefly look into what a class, object, methods, and instant
variables mean.
 Object: Objects have states and behaviours. Example: A dog has states - colour, name, breed as well
as behaviours - wagging, barking, and eating. An object is an instance of a class.
 Class: A class can be defined as a template/blueprint that describes the Behaviours/states that object
of its type support.
 Methods: A method is basically a behavior. A class can contain many methods. It is in methods
where the logics are written, data is manipulated and all the actions are executed.
 Instant Variables: Each object has its unique set of instant variables. An object's state is created by
the values assigned to these instant variables.
C++ Program with Syntax
#include <iostream>
using namespace std;
// main() is where program execution begins.
int main()
{
cout << "Hello World"; // prints Hello World
return 0;
}
The first line, which is:
#include<iostream>
Indicates that the "iostream" header file has been included in the program. As a result, we have access to all
of the objects that are available or defined in it. The term "iostream" refers to a "Input/Output Stream." This
header file was included so that I could use its object "cout" to output text to the output console.
Now let's come to the second line of code, which is:
Using namespace std;
Which is used when all standard namespaces must be used without the "std : :" prefix. The majority of C++
programmers used this line of code before the "main()" method to avoid writing "std::" before "cout" and
"cin," as well as all other methods in the "std namespace." That is, if we remove this line of code, we must
rewrite the preceding C++ program as follows:
#include<iostream>
int main ()
{
cout << "Hello World"; // prints Hello World

Pallavi C S Assistant Prof. Dept. of Data Science AIT, Chikkamagaluru Page 4


Introduction to C++ Programming BPLCK205D
return 0;
}
As a result, if your C++ program contains multiple "cout" and "cin" functions, as well as other functions
from the "std namespace," it is best to use a single line of code to avoid writing "std::" before each "std
namespace" function. However, I do not believe that professional C++ programmers should use "using
namespace std;" to avoid conflicting names. To avoid this conflict, put related or required namespaces right
Before the name.
Now let me explain the third line of code, which is:
int main ()
This line of code will be found in each and every C++ program. This can be called the "main ()" function.
The "main ()" function is that from which the execution of the program starts.
The "int" is the data type, and the data type before any function definition means that the function
will return the value of that type. Therefore, I have written "return 0;" as the last statement of the "main ()"
function.
Now I have an opening curly bracket, which indicates that the definition of the function starts. Then I
wrote the following code:
cout << "Hello World"; // prints Hello World
Which prints the text “Hello World.” on the output console? Because "cout" is an object of the class
"iostream," it is used to output the data to the standard output device such as a monitor.
Then I used the following last line of C++ code:
return 0;
This means that the function "main ( )" has finished successfully. The closing curly bracket then indicates
that the "main ()" function definition is complete.

Major Pillars of OOP C++/Feature

 Class: A Class is a user defined data-type which has data members and member functions. Data
members are the data variables and member functions are the functions used to manipulate these

Pallavi C S Assistant Prof. Dept. of Data Science AIT, Chikkamagaluru Page 5


Introduction to C++ Programming BPLCK205D
variables and together these data members and member functions defines the properties and behavior
of the objects in a Class.
Example:

 Object: An Object is an identifiable entity with some characteristics (Properties) and behavior
(Method). An Object is an instance of a Class. When a class is defined, no memory is allocated but
when it is instantiated (i.e. an object is created) memory is allocated.
Example:

 Abstraction: Data abstraction is one of the most essential and important features of object-oriented
programming in C++. Abstraction means displaying only essential information and hiding the
details. Data abstraction refers to providing only essential information about the data to the outside
world, hiding the background details or implementation. Abstraction using Classes, Abstraction in
Header files

 Inheritance: The capability of a class to derive properties and characteristics from another class is
called Inheritance. Inheritance is one of the most important features of Object-Oriented
Programming. Sub Class, Super Class, Reusability.

Pallavi C S Assistant Prof. Dept. of Data Science AIT, Chikkamagaluru Page 6


Introduction to C++ Programming BPLCK205D
Example:

 Encapsulation: In normal terms, Encapsulation is defined as wrapping up of data and information


under a single unit. In Object-Oriented Programming, Encapsulation is defined as binding together
the data and the functions that manipulate them.
Example:

 Polymorphism: The word polymorphism means having many forms. In simple words, we can define
polymorphism as the ability of a message to be displayed in more than one form. Operator
Overloading: Function Overloading
Example:

 Message/Method: A request for an object to perform one of its operations is called message
operation method/function. All communication between object is done via message is called message
passing

Pallavi C S Assistant Prof. Dept. of Data Science AIT, Chikkamagaluru Page 7


Introduction to C++ Programming BPLCK205D

OBJECT-ORIENTED PROGRAMMING
Object orientation, as mentioned earlier, is an outcome of the research to find the solution to programming
large systems. There are many issues related to object orientation as it has become a discipline of its own
today.
Object-based programming: Object-based programming uses objects and classes but without inheritance.
It provides flexibility to the program and is easier to work with. Operator overloading, function overloading,
and the use of constructors and destructors are included in object-based programming.
Object-oriented programming: Object-oriented programming uses classes and objects with inheritance. It
can have classes inherited from other classes and have complex means for calling and using functions of
both the classes. Base (or parent) classes (from which we derive or inherit another class) and inherited or
derived (from base classes) classes are the two categories of classes.
Example: Suppose we are given a job to write a program about maintaining the roll call of a college using a
C++ program. The roll call is usually done by calling the student’s roll number or name one by one and
making an entry in the register, by using a special sheet where in every student present in the class should
sign, or through a card-based system, which automatically registers a student when he/she approaches the
classroom. This register, sheet, or computer file is then used to provide input to the program. The program
should then be able to generate reports such as the individual attendance of a student and the attendance for a
particular subject.
To program for the roll call process, we have to decide the entities involved in that process. The first
observation yields some entities that are listed here. This list is based on the author’s observation. Readers
may come up with lists with a few differences. There are no clear-cut guidelines for choosing the entities; it
is more a task involving intuition. The author’s list of entities involved in the roll call program, as shown in
Fig. 1.1 is as follows:
1. The teacher who is responsible for taking the roll call
2. The subject for which the roll call is taken

Pallavi C S Assistant Prof. Dept. of Data Science AIT, Chikkamagaluru Page 8


Introduction to C++ Programming BPLCK205D
3. The roll call itself, where the other details about roll call, for example, the day and time of the roll call, the
subject for which it is taken, and so on, are stored. The attendance entries are made for each roll call
separately. Individual roll call forms the basis for calculating subject-wise, teacher-wise, or student-wise
attendance at later stages.
4. The student who is marked present or absent in a given roll call

Fig 1.1: Entities of a system


For our discussion, it is not necessary to follow the complete system design knowledge. Figure 1.2
represents a small system related to students. Four different programs have been considered as a part of the
system here. Usually, we have many programs in the system, but we consider only these four programs for
introduction. The first program is the roll call management, the second is mark sheet printing, the third is
maintaining the subject (i.e., provide adding, deleting, and modifying details of a subject), and the fourth is
maintaining the teacher’s information (i.e., providing adding, deleting, and modifying details of a teacher).
There are five entities considered—roll call, teacher, student, mark sheet, and subject. Again, there are
possibly many more, but they have not been considered for simplicity. Figure 1.2 shows the association of
each entity with each program. The actual system design process might generate a large number of programs
and a larger number of entities in more than one way. The following example will illustrate the concept.

Pallavi C S Assistant Prof. Dept. of Data Science AIT, Chikkamagaluru Page 9


Introduction to C++ Programming BPLCK205D

Fig 1.2: Inter-relationship between programs and entities

Fig 1.2(a): Determining relations among entities

Figure 1.2(a) shows an example of a message being asked and replies being sought from an entity. The
question or the query is normally referred to as a request and the reply is termed as the response. a teacher
asking how many students were present on a particular day in the class and the roll call entity answering that
question. We may need to find out how many such questions are possible to be asked and how the answers
to these questions are sought out. This is the next assignment when we are developing our system. The
method to generate the answer of a message must be provided to the receiving entity; otherwise, the
receiving entity cannot answer that question. In the case of the question regarding the number of students
present, the roll call entity must have a method to calculate the total students present from the data it has.
This method is called or invoked by the receiving entity when the other entity asks for that specific
information.
1.5 What is an object, Classes
A class is an extension to the C struct. The struct Student in C will contain only the attributes of the student
such as name and address.

Pallavi C S Assistant Prof. Dept. of Data Science AIT, Chikkamagaluru Page 10


Introduction to C++ Programming BPLCK205D
struct Student
{
str name;
str addres.;
}
On the other hand, in C++, the class Student will have the attributes of the student and it will also store the
actions (or functions) related to the student. This means that the student class will contain the student name,
address, roll number, subjects, etc., as well as all actions in the form of functions to be performed on the
variables of that class or by the variables of that class
class Student
{
public:
str name;
int roll number
str subjects;
{
cout<<”the name is:”<<name;
}
}
There is one design methodology that demands that classes be designed with minimal member
functions. It says that when we design classes, we should not keep a function as a member function unless it
is necessary. This will make a class ‘thin’ and easy to modify or extend.
We must understand the difference between the student class and the student object. A class is a data
type and an object is a variable of that data type.
A Student class is an abstraction describing what a student object should have name, address, etc. and
should do printing details, accepting details, checking whether passed or not, etc. but does not do anything
itself.
A student object is an instance of that class, which actually has a name, an address, etc. A class is a
sketch from where actual objects are derived. The action performed by the objects is known as method in
object-oriented programming, but C++ calls it function. So we will use the word ‘function’ to describe the
action that is performed on or by an object of the class.
The functions that are a part of the class are known as member functions. It is also possible to have
functions that do not belong to any class; such functions are known as non-member functions. In C struct,
functions are not a part of the struct; if they need to operate on a structure, it is passed to them.

Pallavi C S Assistant Prof. Dept. of Data Science AIT, Chikkamagaluru Page 11


Introduction to C++ Programming BPLCK205D
In C++, it is possible to write a member function that is known only to that class, and the rest of the
program is not aware of it. There is no direct way to call that member function using objects of other classes.
Thus, the objects of class Student can call StudentPrintDetails, but the objects of class dog cannot call this
function. This is one of the fundamental differences between C and C++. Thus, we can write
Lara.PrintDetails ( ) but we cannot write Snoopy. PrintDetails ( ). It should be noted that member functions
are called using dot notation similar to other data elements. The functions now belong to the class.
The definition of a class is similar to the C struct, as we have mentioned earlier. We can define class
Student and can have, say, Student_1 as an object of type Student. If we define class Teacher and then define
Bob as a variable of type Teacher, Teacher is a class where Bob is an object.
Object-oriented View of Classes and Objects:
The class is a representation of the real-world entity or an entity added by a programmer for convenience
with respective attributes that are required to solve the problem at hand. It can be seen that this description is
quite vague. For a given problem, the set of entities that the author has chosen probably is different from that
chosen by the readers. The same problem is being solved but handled differently. Moreover, the attributes
that the author has chosen probably are very different from that of the readers, even if both are solving the
same problem.
All entities that are modelled in the program are implemented as classes. Thus, the classes in one
program could be different from that in another when solving the same problem. Such classes do not refer to
an individual entity, but we refer to them in general. The entities such as Ganesh as a student, Mathew as a
teacher, or roll call 16030903 are instances of the generic entities that we have discussed so far. In object-
oriented parlance, they are known as objects. Objects are variables of type class and can be defined similar to
variables. Assuming that the classes Student, Teacher, and RollCall,
The following are valid C++ statements, which define the individual entities or objects for respective
classes:
Student Ganesh;
Teacher Mathew;
RollCall RollCall16030903;
In these definitions, the left-hand side (LHS) part is the data type and the right-hand side (RHS) part is the
variable. Once the classes have been defined, the class name can indeed be used as a data type. So, in this
case, the classes are Student, Teacher, and RollCall. The instances of these classes are Ganesh, Mathew, and
RollCall16030903, which are also called the objects of the respective classes.
It is also important to understand that a single class usually has multiple objects associated with it. For
example,
Student Mahesh, Jagruti, Rama, Haresh;
Here, we have a single class Student with which we have four objects associated.

Pallavi C S Assistant Prof. Dept. of Data Science AIT, Chikkamagaluru Page 12


Introduction to C++ Programming BPLCK205D

Fig 1.3: Some classes and their objects.


Abstract Data Type:
When the objects of a class behave like a data type, the class is known as an abstract data type (ADT).
The string class is an example of ADT. It is possible to define a complex number as a data type using a class.
Similarly, we can also define graphic concepts such as point, circle, and rectangle as a class such that the
objects behave like a data type. We can write the following statements after properly defining these ADTs.

Complex C1 (2,3), C2;


Point P (2,3), Q(4,S), R(10,10),S;
Circle C (P, 20), Ring;
Rectangle Rect (P, R), PlayGround;

These ADTs are defined in two ways, one with initialization and the other without. For example, Point P
(2,3) not only defines a point P but also defines that the x and y coordinates of the point P are 2 and 3. On
the other hand, point S is defined without any mention of the coordinates.
Quite a few useful class definitions fall under the category of ADT, including stack, queue, string,
vector, and dequeue. We will learn about complex, point, circle, and rectangle while we discuss operator
overloading.

1.6 Methods and messages

Teacher SomeTeacher;
SomeTeacher = RollCall16030903.getTeacher ( );

The code for providing response to the message is known as method.


The first statement defines an object SomeTeacher of the class Teacher. This definition looks similar to a
variable SomeTeacher being defined of the type Teacher. This is indeed so. Here, Teacher is known as a

Pallavi C S Assistant Prof. Dept. of Data Science AIT, Chikkamagaluru Page 13


Introduction to C++ Programming BPLCK205D
user-defined type and SomeTeacher is a variable of that type, that is, the object of the class Teacher. Similar
to other variables, this variable can also be used on the LHS of the assignment statement to assign a specific
value to it. Whenever such an object is used as an LHS expression of an assignment statement, the outcome
of the RHS expression is assigned to the object.
Message Passing:

Fig1.4: Message, method, and optional response


A more important part is the call to the function, which is defined inside the class RollCall. The function can
be called by using the object<dot>function name syntax. The function getTeacher ( ) is part of the RollCall
class we assign the Teacher object (object representing Mathew in our case) returned by that function to
SomeTeacher. The getTeacher() function here must be designed to return the Teacher object.

SomeTeacher = RollCall16030903.getTeacher ( );

In the entire discussion so far, the getTeacher () function is known as a message being passed to an object
RollCall16030903. The object takes some action (executes the body of the function specified, the getTeacher
() function in our example) and returns with the response show in figure 1.5

Fig1.5: Message, method, and no response

Pallavi C S Assistant Prof. Dept. of Data Science AIT, Chikkamagaluru Page 14


Introduction to C++ Programming BPLCK205D
In fig: 1.5 Assume that DispInfo() is a function defined in the Teacher class, which displays everything that
one would like to know about the teacher, and that we have defined Gary as a teacher. We may type Gary.
DispInfo(); and the function will display all information about Gary. Here, the message to display all
information is sent to the object of the Teacher class (the object named Gary). In response, the object
manages to execute the function DispInfo() and display the information needed. Here, the object does not
need to respond with any information. Thus, the response is optional.

Fig 1.6: Message, method, and optional response for a motorbike

1.7 Abstraction and encapsulation


Abstraction:
It is important for the system to keep the method hidden from the user for the sake of simplicity.
Think of the case when one presses the brake pedal and the brakes are applied. All the circuitry that applies
the brake is not open to us. What is the advantage of hiding the circuitry? This simplifies our view. We only
find the brake pedal to work with. Opening up the circuitry may not make any difference to an experienced
bike rider but consider the case of a novice. If everything is open to him/her, it will take quite some time for
him/her to figure out how to apply the brakes. The possibility of pressing something other than the brake
pedal is also possible. The bottom line is to expose only those entities that the user needs to interact with and
hide everything else. This important law is also observed in C++. It is known as the law of abstraction,
explained in Exhibit
Law of abstraction: Whenever a programmer designs a class, he/she designs it in a way that only those
messages that the user is concerned about can be passed to the object and their responses are sought. How
the messages are responded to be not seen. No other messages can be passed to the entity.
For example, we can pass messages such as getTeacher ( ), getSubject ( ), and Is Student Present
(Student) to extract data from the RollCall object and get suitable responses. How- ever, we may not be able
to send an UpdateRollCallValue() message if such a message is not expected to be received by the RollCall
object. We can only send and get responses to valid messages.

Pallavi C S Assistant Prof. Dept. of Data Science AIT, Chikkamagaluru Page 15


Introduction to C++ Programming BPLCK205D

Fig 1.7: Abstraction implemented as combination of exposed (public) and hidden (private) parts
Encapsulation:
The process of designing a class with some attributes hidden and some exposed is known as
encapsulation. The entire class is insulated from the outside world. Only the public (or exposed) attributes
can be manipulated by the user of that object. Thus, we can have controlled access to the class attributes
unlike struct in C. If we define a struct Student with attributes such as name, address, and roll number, then
all the attributes are available for manipulation. However, in C++, it is possible to define a class Student
where we cannot directly manipulate the name, address, and roll number, but we can only set their values
using a function InsertDetails ( ) and print the information using PrintDetails ( ). Objects have two different
types of attributes.

Fig 1.8: Encapsulation process

Pallavi C S Assistant Prof. Dept. of Data Science AIT, Chikkamagaluru Page 16


Introduction to C++ Programming BPLCK205D
The exposed attributes can be manipulated and supplied with inputs, whereas the hidden attributes are meant
for internal execution. Such insulation of the class from the rest of the program is called encapsulation. The
class attributes are encapsulated within the class and only the public part of it is accessible to the user of the
object of that class. The private part is only accessible to those functions that are a part of the capsule, as can
be seen in Fig. 1.8.
The class contains both data and function attributes as part of the capsule. The rest of the program that uses
the objects of this class can only access the public part. Sometimes encapsulation is referred to as combining
the data and function together in the class body. The correct way to look at encapsulation is the division of
class members in public and private and the idea of hiding the unnecessary and complex part from the user
of the object. Encapsulation and abstraction together make the complex system visible as a simpler system.
*Designing a class with public and private attributes carefully makes a complex system easy to work
with for the programmer. It helps in hiding the unnecessary things and reveals only those things that
are useful for the programmer.*

A programmer may define a class as follows, separating the private and public members:
class Dummy
{
private:
...
public:
...
}

1.8 Inheritance
The idea of extending an already defined class is known as inheritance. if we are writing a program to
maintain the object MCAStudent and we have a built-in class Student, which has almost all the details
needed for our program, except a few, which need to be added manually. The additional information may be
anything that an MCA student possesses in addition to the normal student.
Let us now look at inheritance from the point of view of object orientation. The world is full of cases
where one class is a specialization of another. Human beings are a specialization of mammals; dogs are a
specialization of animals; Indians are a specialization of people. This relationship between two different
classes is significant in more than one way.
There can be quite a large number of relationships possible between any two given entities. Inheritance
(or specialization) is one such relationship, where one class inherits all the attributes of some other class

Pallavi C S Assistant Prof. Dept. of Data Science AIT, Chikkamagaluru Page 17


Introduction to C++ Programming BPLCK205D

Fig 1.9: Some classes and inherited subclasses


The inheritance relationship is sometimes compared with an is-a relationship, which is similar to the
mathematical notion of a subset relationship. The word ‘is-a’’ is derived from the fact that we can usually
ask the question ‘x is a y?’ to find if x is inherited from y. whenever we have an is a relationship between
two entities
Take the case of numbers. We know that N (the set of natural numbers 1, 2, 3, … until ∞) is a subset
of R (the set of real numbers). Is N inherited from R? It is difficult to understand this. It is better to put forth
the question as: ‘Is an element of N also an element of R?’ If the answer is yes, N is said to have an is-a
relationship with R.
 Advantages of Deploying Inheritance
The object-oriented languages including C++ provide means for having inheritance relationship between any
two classes. One important reason for such a facility being provided in the language is that inheritance is one
intuitive way to model the real-world hierarchy in the program.
Suppose we are programming for graphics shapes and we already have the rectangular shape as a
class. Now, we can add square to it using inheritance by providing the specialization that a square is a
rectangle, where the length equals the width. Similarly, ellipse can be inherited into circle, and so on. It is
possible to model hierarchy like this in C++.
Reduction in work: One important outcome of modelling this inheritance hierarchy is the reduction in
work. We may have defined a function for calculating the area in the rectangle class, and when we define a
new class square, which is inherited from the rectangle class, the area function is available to the square class
automatically. This feature is sometimes referred to as reusability. Reusability is the property of the
attributes of the object to be reused in a way such that the maximum utilization of the design is possible
Myths
Myth 1: for reusability, inheritance is an ideal tool to be used. Whenever one needs to have reusability,
he/she should opt for inheritance.

Pallavi C S Assistant Prof. Dept. of Data Science AIT, Chikkamagaluru Page 18


Introduction to C++ Programming BPLCK205D
The first statement is wrong as reusability is an advantage obtained from providing inheritance, but it is not
good to opt for inheritance whenever we need to reuse some code. Inheritance should be used only when the
class inherited (the derived class) is indeed the specialization of the class inherited from (the base class).
Otherwise, unforeseen consequences can occur, and the program design may become rigid and difficult to
extend or evolve. Thus, when we want to have some functions in our class, which are available in some
other class, we should not inherit from that class unless it has an is-a relationship with that class. Reiterating
an important point again, please note that when we use inheritance we get reusability as a side effect and it is
a great advantage, but to use inheritance to gain the advantage of reusability is wrong and indicates bad
design. A discipline in the programmer community is required to maintain this.
Myth 2: Inheritance is the only way to provide reusability in any object-oriented language.
The second statement is also untrue as there are other ways of reusing the same code. C++ provides
templates to reuse the code as well as the class definitions. STL, The providing reusability without using
inheritance. It is also possible to merge the templates and inheritance to provide reusability.

1.9 Abstract classes


An abstract class is a class with no object. An abstract class contain at least one pure virtual function.
Classes can be designed in the top-down as well as the bottom-up way.
There are two different types of entities. One type of entity is directly modelled from the real-world
counterpart, that is, a student or a teacher. The other type is what a programmer is required to add to
the system to effectively solve the problem..
There is one more way of looking at the category of classes. The first type of class has a real-world
counterpart existing in reality, most of the time having a tangible existence. The other type is the real-world
counterpart that exists only in abstract.
Take the case of the animal class. An animal is an abstract concept. The animal class does not have any
direct object. Every animal is a dog, a tiger, a lion, or something similar. All these classes are derived from
the animal class and due to the transitivity of relationship (A → B and B → C, so A → C), a dog, a tiger, or
a lion is an animal. Snoopy is a dog, so it is an animal as all dogs are animals. Here, Snoopy is not a direct
object of the animal class. Plenty of such abstract concepts exist in the real world, and when we need to use
them, we should define abstract classes.
One more alternative, but a more practical design, is to learn about the common attributes while working
with the first two types of classes and then to program for a CEStudent. Here, the design for CEStudent class
becomes easier as it does not need to include anything that is available in the Student class. It is
automatically available after inheritance. This is also similar to the real-world case as when we say that man
is a mammal, we do not need to ask if man breathes or not. Since all mammals breathe, man having an is-a

Pallavi C S Assistant Prof. Dept. of Data Science AIT, Chikkamagaluru Page 19


Introduction to C++ Programming BPLCK205D
relationship with the mammal must do so. Unless explicitly stated otherwise, the relationship holds true.
Sometimes though, it does not.
Steps for designing classes using a bottom-up approach
1. We have the CSStudent class defined first
2. Now we have CSStudent as well as ITStudent
3. Finding out common attributes and generating student class from it
4. It helps in defining CEStudent

Fig 1.10: Steps for designing classes using a bottom-up approach


 There is no redundancy:
The student’s name is kept only in the Student class. If we need to change the size or type of the
name, we have to change at only one place, the Student class, and nowhere else. As other classes
inherit from this class, all of them have the effect of the change automatically.
Hence, there are less chances of ambiguity. Assume that we are not using the base class approach. It
is quite possible that the same attribute in two different classes have two different names. Suppose in one
class the name of the student is defined as StudName, in the second class the name is defined as Name, and
the third class probably calls it StudentName. More than one class representing the same real-world entity or
more than one attribute name referring to the same attribute creates a lot of ambiguity in the designer’s and
developer’s mind. This is eliminated here as there is a single class, and the name given to the attribute
student name (say StudNm) is the same in all classes because these classes do not define this attribute
themselves, but they just inherit them.

Pallavi C S Assistant Prof. Dept. of Data Science AIT, Chikkamagaluru Page 20


Introduction to C++ Programming BPLCK205D
 Adding a new attribute to all the classes is simple:
Suppose we would like to add mobile number as an additional attribute to all three classes, we can
do it by placing it in the Student class. We do not need to pick each class one by one and do it
individually.
This example indicates why the word ‘abstract’ is chosen. Shape is an abstract concept, which does
not have any object associated with it. There are quite a few other abstract concepts such as furniture or
electric equipment in the real world, but there are no entities that we can call only furniture or electrical
equipment. The entity that is furniture will invariably be a sofa, a chair, or something similar, but not
‘furniture’ by itself. Similarly, electrical equipment is either a bulb, a holder, or something similar, but not
electrical equipment

Fig 1.11: Abstract base classes and inherited subclasses


The following is an example of inheritance. The class Shape is inherited into Rectangle and Circle.
Rectangle is also inherited into Square. It can be seen that Rectangle and Circle are specializations of Shape,
and square is a specialization of Rectangle. The word public means the inheritance is of type public.

class Shape {…};


class Rectangle: public Shape {…}
class Circle: public Shape {…}
class Square: public Rectangle {…}

1.10 Polymorphism
In general, polymorphism is the ability of a single object to appear in many forms. Polymorphism is
related to something that behaves differently under different circumstances. One may be a student in a

Pallavi C S Assistant Prof. Dept. of Data Science AIT, Chikkamagaluru Page 21


Introduction to C++ Programming BPLCK205D
college or an employee in a working place. The same person may be a son or a daughter at home and a
friend when sitting with a group of friends. One may respond to ‘How are you doing?’ differently when
playing different roles. The idea is to react differently for the same message in different situations. If one
does so, he/she is exhibiting polymorphism.
Polymorphism allows an object to behave differently under different circumstances, given the same
message.
Many types of polymorphism exist but we will discuss the following three different versions, which
have some relation to C++.
1.10.1 Ad-hoc Polymorphism at Compile Time
This type of polymorphism is related to functions that behave differently with different sets of
arguments. It is possible to define the same function with different types of arguments or different
number of arguments in C++.

Fig 1.4: Polymorphism arising from argument set


Here, we have defined three different functions with the same name (Add) but with either different sets of
arguments or different number of arguments or both. All function bodies are different, and thus, we observe
a different response when we call the same Add () function with either different sets of arguments or
different number of arguments. For example, when we call Add(int, int), we get the addition of two integer
values returned from the function, and when we call Add(int, int, int), the function does not return anything
but the third argument now contains the summation. Providing different behaviour in different contexts
(number or arguments) is known as function overloading in C++.
Type of the following is the various types of Add () function:
1. Add (int First, int Second)
2. Add (float First, float Second)

Pallavi C S Assistant Prof. Dept. of Data Science AIT, Chikkamagaluru Page 22


Introduction to C++ Programming BPLCK205D
3. Add (string First, string Second)
4. Add (int First, int Second, int Third)
5. Add (int first, float Second)
6. Add (int First, float Second, float Third)

Fig 1.5: Polymorphism arising from operand types


12 + 25 (Result is 37)
12.0876 + 25.98 (Result is 38.0676)
'Indian' + 'Cricketer' (Result is 'IndianCricketer')

The + operator in these three cases behaves differently. In the first case, it adds two integers; in the
second case, it adds two double values; and in the third case, it concatenates two different strings into one.
The string is available in C++ as a data type. + is overloaded in the string class. So, the given operation
makes sense. When the operator behaves differently for different types of operands, it is also a type of
ad-hoc polymorphism. In C++ parlance, this is called operator overloading.
In C++, both function and operator overloading are resolved at compile time. The compiler, while
compiling the program, decides the operation to be performed and generates the object code that describes
that operation. In the given example, when 12 + 25 is seen in the source code, the compiler provides the code
that adds two integer values and adds that to the object code being generated and when ‘Indian’ + ‘Cricketer’
is seen, it adds the string concatenation routine at that place.
1.10.2 Dynamic Polymorphism at Run-time
This is a case when the resolution of the function happens at run-time. The restriction here is to choose the
function only from the hierarchy of classes and not from elsewhere.

Pallavi C S Assistant Prof. Dept. of Data Science AIT, Chikkamagaluru Page 23


Introduction to C++ Programming BPLCK205D

Fig 1.6: An example of a hierarchy for run-time polymorphism


 Suppose we define Student as a base class.
 Then, we define three derived classes, CSStudent, ITStudent, and CEStudent, from Student.
 Next, we define function getAttendance () in all these classes. (It is important to define this function
as virtual to achieve polymorphism.
 Now, we define a pointer to the base class Student. Let us call it PtrStudent. It is important to note
that this pointer can point to an object of any class in the hierarchy mentioned.
 Whenever we type PtrStudent->getAttendance () (i.e., execute the function getAttendance () of the
object PtrStudent is pointing to at the moment), the member function of the object being pointed to is
executed.
So, if our PtrStudent is pointing to Ganesh, a CS student, a function getAttendance ( ) defined in CSStudent
class will be executed. When the same pointer points to Mahesh, an IT student, the getAttendance ( ) defined
inside the ITStudent is executed. Both the getAttendance ( ) functions could be quite different.
For example, in the CSStudent case, only the theory class attendance is returned, whereas in the
ITStudent case both the theory and the practical attendance are returned.
The caller does not need to modify his/her call even if the functions behave differently. This is
known as dynamic polymorphism, as it requires dynamic information about where the pointer is pointing to
at run-time. Sometimes, this polymorphism is also referred to as subtyping or inclusion polymorphism. As
mentioned earlier, the function getAttendance () mentioned here is to be defined as virtual in C++ to achieve
the effect of polymorphism.
The following code snippet shows how polymorphism is provided using virtual functions.

/* assuming class Student is defined with a virtual function


getAttendance ( ) and all the three classes CSStudent, ITStudent, and
CEStudent are inherited from Student */

Pallavi C S Assistant Prof. Dept. of Data Science AIT, Chikkamagaluru Page 24


Introduction to C++ Programming BPLCK205D
ITStudent Mahesh;
CSStudent Ganesh;
Student Jayesh CEStudent;
Student *ptrStudent;
...
ptrStudent = *Mahesh;
ptrStudent -> getAttendance ( )
// it calls the getAttendance ( ) function of ITStudent class
ptrStudent = *Ganesh;
ptrStudent -> getAttendance ( )
// it calls the getAttendance ( ) function of CSStudent class

1.10.3 Parametric Polymorphism


The third type of polymorphism seen in C++ is known as parametric polymorphism. Using parametric
polymorphism, a function or a data type can be written generically so that it can handle values
identically without depending on their type.
C++ provides templates as type less descriptions of classes and functions to provide parametric
polymorphism. While programming with parametric polymorphism, we can code functions and classes
without specifying their type, and when they are used, the type is passed as an argument. This type-
resolution process happens at compile time in C++, so it is a kind of compile type polymorphism.

Pallavi C S Assistant Prof. Dept. of Data Science AIT, Chikkamagaluru Page 25


Introduction to C++ Programming BPLCK205D
ASSIGNMENT QUESTIONS FOR INTRODUCTION TO C++ PROGRAMMING
MODULE‐1
Q1 Discuss Evolution of Computer programming (Page No 1)
Q2 List out Feature and Benefits of Object Oriented Program (Page No 2)
Q3 Illustrate The Structure of C++ Program with Syntax and Example(Page No 4,5)
Q4 Write a C++ Program to Display as
Subject Name = Object Oriented Programming
Subject Code = BPLCK205D
Q5 Discuss the Fallowing terms with suitable examples(Page No 6,7,8)
a. Class
b. Object
c. Abstraction
d. Inheritance
e. Encapsulation
f. Polymorphism
g. Message/Method
h. Abstract Data Type
Q6 Illustrate what is an object Classes with Simple Program? How Object-oriented View of Classes and
Objects with Suitable Diagram (Page No 10,11,12,13)
Q7 Explain message passing in with a optional response and no response suitable example. (Page No
14,15)
Q8 Write the Law of Abstraction? Explain Encapsulation Briefly? (Page No 15,16,17)
Q9 What is Advantages of Deploying Inheritance? State the Myths of Inheritance. (Page No 18,19)
Q10 What are abstract classes? Where are they useful (Advantages)? Discuss with an example (Page No
19,20)
Q11 What is Polymorphism? Explain with Different Version of Polymorphism With Suitable Example
(Page No 21,25)

Pallavi C S Assistant Prof. Dept. of Data Science AIT, Chikkamagaluru Page 26

You might also like