Object Oriented Programing UNIT 1,2,3
Object Oriented Programing UNIT 1,2,3
Object Oriented
Programming
and
Data Structures
SYBCA
[ FOR UNIT-1,2,3 Only ]
Divided Into In POP, program is divided into small In OOP, program is divided into parts
partscalled functions. called objects.
Importance InPOP, Importanceis not given In OOP, Importance is given to the data
to data but to functions as well rather than procedures or functions
as sequence of actions to be done. because it works as a real world.
Approach POP follows Top Down approach. OOP follows Bottom Up approach.
AccessSpecifies POP does not have any OOP has accessspecifiesnamed Public,
accessspecified. Private, Protected, etc.
Data Moving In POP, Data can move freely from In OOP, objects can move and
function to function in the system. communicate with each other through
member functions.
Expansion To add new data and function in OOP provides an easy way to add new
POP is not so easy. data and function.
Data Access In POP, Most function uses Global In OOP, datacannotmove easily from
data for sharing that can be function tofunction, itcan be kept public or
accessed freely from function to private so we can control the access of
function in the system. data.
Data Hiding POP does not have any proper way OOP provides Data Hiding so
for hiding data so it is less secure. provides more security.
Overloading In POP, Overloading is not possible. In OOP, overloading is possible in the form
of Function Overloading and Operator
Overloading.
Examples Example of POP is:C, VB, Example of OOP is:C++, JAVA, VB.NET,
FORTRAN,and Pascal. C#.NET.
2
The major motivating factor in the invention of object-oriented approach is to remove
some of the flaws encountered in the procedural approach. OOP treats data as a critical
element in the program development and does not allow it to flow freely around the system. It
ties data more closely to the function that operate on it, and protects it from accidental
modification from outside function. OOP allows decomposition of a problem into a number of
entities called objects and then builds data and function around these objects.
Some of the features of object oriented programming are:
Objects
Objects are the basic run time entities in an object-oriented system. They may represent
a person, a place, a bank account, a table of data or any item that the program has to handle.
They may also represent user-defined data such as vectors, time and lists.
Programming problem is analyzed in term of objects and the nature of communication
between them. Program objects should be chosen such that they match closely with the real-
world objects.
Objects take up space in the memory and have an associated address like a record in
Pascal, or a structure in c.
When a program is executed, the objects interact by sending messages to one another.
For example, if “customer” and “account” are to object in a program, then the customer object
may send a message to the account object requesting for the bank balance.
3
Each object contain data, and code to manipulate data. Objects can interact without
having to know details of each other’s data or code. It is a sufficient to know the type of
message accepted, and the type of response returned by the objects.
Classes
We just mentioned that objects contain data, and code to manipulate that data. The
entire set of data and code of an object can be made a user-defined data type with the help of
class.
In fact, objects are variables of the type class. Once a class has been defined, we can
create any number of objects belonging to that class. Each object is associated with the data of
type class with which they are created.
A class is thus a collection of objects similar types. For examples, Mango, Apple and
orange members of class fruit.
Classes are user-defined Data types and behave like the built-in types of a programming
language. The syntax used to create an object is not different then the syntax used to create an
integer object in C.
If fruit has been defines as a class, then the statementFruit Mango;Will create an object
mango belonging to the class fruit.
Encapsulation
The wrapping up of data and function into a single unit (called class) is known as
encapsulation. Data encapsulation is the most striking feature of a class.
The data is not accessible to the outside world, and only those functions which are
wrapped in the class can access it. These functions provide the interface between the object’s
data and the program.
This insulation of the data from direct access by the program is calleddata hidingor
information hiding.
Abstraction
Abstraction refers to the act of representing essential features without including the
background details or explanation.
Classes use the concept of abstraction and are defined as a list of abstract attributes
such as size, wait, and cost, and function operate on these attributes. They encapsulate all the
essential properties of the object that are to be created.
The attributes are some time called data members because they hold information. The
functions that operate on these data are sometimes called methods or member function.
4
Inheritance
Inheritance is the process by which objects of one class acquired the properties of
objects of another classes. It supports the concept of hierarchical classification.
For example, the bird, ‘robin’ is a part of class ‘flying bird’ which is again a part of the class
‘bird’. The principal behind this sort of division is that each derived class shares common
characteristics with the class from which it is derived.
In OOP, the concept of inheritance provides the idea of reusability. This means that we
can add additional features to an existing class without modifying it. This is possibleby deriving
a new class from the existing one. The new class will have the combined feature of both the
classes.
The real appeal and power of the inheritance mechanism is that it allows the
programmer to reuse a class that is almost, but not exactly, what he wants, and to tailor the
class in such a way that it does not introduced any undesirable side-effects into the rest of
classes.
Polymorphism
Polymorphism, a Greek term, means the ability to take more than on form. An
operation may exhibit different behavior is different instances. The behavior depends upon the
types of data used in the operation.
For example, consider the operation of addition. For two numbers, the operation will generate
a sum. If the operands are strings, then the operation would produce a third string by
concatenation. The process of making an operator to exhibit different behaviors in different
instances is known as operator overloading.
A single function name can be used to handle different number and different types of
argument. This is something similar to a particular word having several different meanings
depending upon the context. Using a single function name to perform different type of task is
known as function overloading.
Polymorphism plays an important role in allowing objects having different internal
structures to share the same external interface. This means that a general class of operations
may be accessed in the same manner even though specific action associated with each
operation may differ.
Polymorphism is extensively used in implementing inheritance.
Dynamic Binding
Binding refers to the linking of a procedure call to the code to be executed in response
to the call. Dynamic binding (also CalledLate Binding) means that the code associated with a
given procedure call is not known until the time of the call at run time.
It is associated with polymorphism and inheritance. A function call associated with a
polymorphic reference depends on the dynamic type of that reference.
5
Message Passing
Objects communicate with one another by sending and receiving information much the
same way as people pass messages to one another. The concept of message passing makes it
easier to talk about building systems that directly model or simulate their real world
counterparts.
A Message for an object is a request for execution of a procedure, and therefore will
invoke a function (procedure) in the receiving object that generates the desired results.
Message passing involves specifying the name of object, the name of the function (message)
and the information to be sent.
OOP offers several benefits to both the program designer and the user. ObjectOrientation
contributes to the solution of many problems associated with the development and quality of
software products.
The new technology promises greater programmer productivity, better quality of software and
lesser maintenance cost.
The principal advantages are:
Through inheritance, we can eliminate redundant code extend the use of existing
Classes.
We can build programs from the standard working modules that communicate with one
another, rather than having to start writing the code from scratch. This leads to saving
of development time and higher productivity.
The principle of data hiding helps the programmer to build secure program that can not
be invaded by code in other parts of a programs.
6
It is easy to partition the work in a project based on objects.
“C++ incorporated all these extensions in another user-defined type Known as CLASS”
There is a little syntactical difference in structure and Classes in C++ therefore, they can be used
interchangeably with minor modification.
Note :The only difference between structure and classes in C++ is that ,by default, the
member of a class are private, while by default the members of structure are public.
Specifying a Class
A class in C++ combines related data and functions together. It makes a data type which
is used for creating objects of this type.
Classes represent real world entities that have both data type properties
(characteristics) and associated operations (behavior).
Generally a class specification has two parts :
7
Class Declaration
Class Function definition
Class Declaration
Here, the keyword class specifies that we are using a new data type and is followed by the class
name.
8
Inside Class Definition:
When a member function is defined inside a class, we do not require to place a
membership label along with the function name. We use only small functions inside the class
definition and such functions are known as inline functions. In case of inline function the
compiler inserts the code of the body of the function at the place where it is invoked (called)
and in doing so the program execution is faster.
Name_of_the_class :: function_name
The syntax for a member function definition outside the class definition is :
Here the operator :: known as scope resolution operator helps in defining the member function
outside the class. Earlier the scope resolution operator(::)was is use in situations where a global
variable exists with the same name as a local variable and it identifies the global variable.
Example of Class :
Class student
{
private:
char reg_no[10];
char name[30];
int age;
char address[25];
public :
void init_data()//Inside Class Defenation
{
- - - - - //body of function - - - - -
}
void display_data();
};
void student :: display_data()//Outside class Defination
{
----------//body of function -------
}
9
Ob.init_data();//Access the member function
ob.display_data();//Access the member function
Constructors
A constructor (having the same name as that of the class) is a special member function
which is automatically initialize the data-members (variables) of the class type with legal initial
values.
It is defined like other member functions of the class, i.e., either inside the class
definition or outside the class definition. For example, the following program illustrates the
concept of a constructor:
10
SPECIAL CHARACTERISTICS OF CONSTRUCTORS
We can use a constructor to create new objects of its class type by using the
syntax.
Name_of_the_class (expresson_list)
For example,
Employee obj3 = obj2;
Employee obj3 = employee (1002, 35000); //explicit call
The make implicit calls to the memory allocation and deallocation operators new and
delete.
These cannot be virtual.
Types of Constructors
Overloaded Constructors
Besides performing the role of member data initialization, constructors are no different
from other functions. This included overloading also. In fact, it is very common to find
overloaded constructors. For example, consider the following program with overloaded
constructors for the figure class:
11
//Illustration of overloaded constructors
//construct a class for storage of dimensions of circles.
//triangle and rectangle and calculate their area
#include<iostream.h>
#include<conio.h>
#include<math.h>
#include <string.h>//for strcpy()
Class figure
{
Private:
Float radius, side1,side2,side3;//data members
Char shape[10];
Public:
figure(float r)//constructor for circle
{
radius=r;
strcpy (shape, “circle”);
}
figure (float s1,float s2)//constructor for rectangle strcpy
{
Side1=s1;
Side2=s2;
Side3=radius=0.0;//has no significance in rectangle
strcpy(shape,”rectangle”);
}
Figure (float s1, floats2, float s3)//constructor for triangle
{
side1=s1;
side2=s2;
side3=s3;
radius=0.0;
strcpy(shape,”triangle”);
}
void area()//calculate area
{
float ar,s;
if(radius==0.0)
{
if (side3==0.0)
ar=side1*side2;
else
ar=3.14*radius*radius;
}
12
cout<<”\n\nArea of the “<<shape<<”is : <<ar<<”sq.units\n”;
}
};
Void main()
{
Clrscr();
Figure circle(10.0);//object initialized using constructor
Figure rectangle(15.0,20.6);//object initialized using constructor
Figure Triangle(3.0, 4.0, 5.0);//object initialized using constructor Rectangle.area();
Triangle.area();
Getch();//freeze the monitror
}
Copy Constructors
It is of the form classname (classname &) and used for the initialization of an object
form another object of same type. For example,
Class fun
{
Float x,y;
Public:
Fun (floata,float b)//constructor
{
x = a;
y = b;
}
Fun (fun &f)//copy constructor
{
cout(“\n Copy Constructor at work \n”);
X = f.x;
Y = f.y;
}
Void display (void)
{
Cout<<””<<y<<endl;
}
};
Here we have two constructors, one copy constructor for copying data value of a fun object to
another and other one a parameterized constructor for assignment of initial values given.
13
In C++, we can define constructor s with default arguments. For example, The following
code segment shows a constructor with default arguments:
Class add
{
Private:
Int num1, num2,num3;
Public:
Add(int=0,int=0);//Default argument constructor
//to reduce the number of constructors
Void enter (int,int);
Void sum();
Void display();
};
//Default constructor definition
add::add(int n1, int n2)
{
num1=n1;
num2=n2;
num3=n0;
}
Void add ::sum()
{
num3=num1+num2;
}
Void add::display ()
{
Cout<<”\n The Sum of two number is “<< num3<<endl;
}
Now using the above code objects of type add can be created with no initial values, one initial
values or two initial values. For Example,
Here, obj1 will have values of data members num1=0, num2=0 and num3=0
Obj2 will have values of data members num1=5, num2=0 and num3=0
Obj3 will have values of data members num1=10, num2=20 and num3=0
14
and add::add(int=0);//default argument constructor
Then the default argument constructor can be invoked with either two or one or no
parameter(s).
Without argument, it is treated as a default constructor-using these two forms together causes
ambiguity. For example,
add :: add()
or add :: add(int=0,int=0)
Friend Function
A friend function of a class is defined outside that class' scope but it has the right to
access all private and protected members of the class. Even though the prototypes for friend
functions appear in the class definition, friends are not member functions.
A friend can be a function, function template, or member function, or a class or class
template, in which case the entire class and all of its members are friends.
To declare a function as a friend of a class, precede the function prototype in the class
definition with keyword friend as follows:
class Box
{
double width;
public:
double length;
friend void printWidth( Box box );
void setWidth( double wid );
};
#include <iostream>
class Box
{
double width;
15
public:
friend void printWidth( Box box );
void setWidth( double wid );
};
return 0;
}
A friend function is not in the scope of the class n which it has been declared as friend.
It cannot be called using the object of that class.
It can be invoked like a normal function without any object.
Unlike member functions, it cannot use the member names directly.
It can be declared in public or private part without affecting its meaning.
Usually, it has objects as arguments.
Inline Function
16
These are the functions designed to speed up program execution. An inline function is
expanded (i.e. the function code is replaced when a call to the inline function is made) in the
line where it is invoked. You are familiar with the fact that in case of normal functions, the
compiler have to jump to another location for the execution of the function and then the
control is returned back to the instruction immediately after the function call statement. So
execution time taken is more in case of normal functions. There is a memory penalty in the case
of an inline function.
The system of inline function is as follows :
inline function_header
{
body of the function
}
For example,
//function definition min()
inline void min (int x, int y)
{
cout<< (x < Y? x : y);
}
Void main()
{
int num1, num2;
cout<<”\n enter two integers\n;
cin>>num1>>num2;
min (num1,num2);
//function code inserted here ------------------ ------------------
}
An inline function definition must be defined before being invoked as shown in the
above example. Here min ( ) being inline will not be called during execution, but its code would
be inserted into main ( ) as shown and then it would be compiled.
If the size of the inline function is large then heavy memory pentaly makes it not so
useful and in that case normal function use is more useful.
For functions returning values and having a loop or a switch or a goto statement.
For functions that do not return value and having a return statement.
For functions having static variable(s).
If the inline functions are recursive (i.e. a function defined in terms of itself).
17
The benefits of inline functions are as follows :
Dynamic objects are used when the object to be created is not predictable enough.This
is usually when we cannot determine at compile time
Object Identities
Object Quantities
Object Lifetimes
Therefore when creating Dynamic Objects they cannot be given unique names, so we have
to give them some other identities In this case we use pointers.
Creating Dynamic Objects Dynamic
Objects use dynamic memory allocation In C++ a pointer can be directed to an area of
dynamically allocated memory at runtime This can then be made to point to a newly created
object.
To do this we use the new operator in the following way
Point2D *point1;
First we create a pointer to the Point2D Class using the *,Then we use the new operator
to construct a new instanceto the class Using Dynamic Objects To call a user defined
constructor we use the followingsyntax
To send a message (i.e. use a method) we use the -> 'pointed to' delimiter as follows
cout <GetY();
Apart from these distinctions dynamic Objects behave inthe same as static
18
However it is also possible to define a default destructor This will either be called by the
programmer or by the program when the object falls out of scope
To destroy a dynamic Object the destructor must be called. This is done by using the
delete operator as follows
Example :
#include<iostream.h>
#include<conio.h>
Class colour
{
Int r,b,g;
Colour(int m,int n,int o)
{
r= m;
g= n;
b= o;
}
Void print()
{
cout<<”RBG : ”<< r << b << g;
}
};
Int main()
{
Colour *current;
Current = new colour(1,0,0);
Current -> print();
Delete current;
Current = new colour(1,1,1);
Current -> print();
Delete current;
Return 0;
}
Destructor
19
~name_of_the_class() { }
So the name of the class and destructor is same but it is prefixed with a ~ (tilde). It does not
take any parameter nor does it return any value. Overloading a destructor is not possible and
can be explicitly invoked. In other words, a class can have only one destructor. A destructor can
be defined outside the class. The following program illustrates this concept :
20
{
Add obj1,obj2(5),obj3(10,20)://objects created and initialized
clrscr();
Obj1.sum();//function call
Obj2.sum();
Obj3.sum();
Cout<<”\n obj 1 : “;
Obj1.display();
Cout<<”\n obj2 : “;
Obj2.display();
Cout<<”\n obj 3:”;
Obj3.display();
Getch();
}
The main purpose of C++ programming was to add object orientation to the C
programming language, which is in itself one of the most powerful programming languages.
The core of the pure object-oriented programming is to create an object in code that has certain
properties and methods. While designing C++ modules, we try to see whole world in the form of
objects. For example a car is an object which has certain properties such as color, number of doors,
and the like. It also has certain methods such as accelerate, brake, and so on.
There are a few principle concepts that form the foundation of object-oriented programming:
Object
This is the basic unit of object oriented programming. That is both data and function that operate
on data are bundled as a unit called as object.
Class
21
When you define a class, you define a blueprint for an object. This doesn't actually define any data,
but it does define what the class name means, that is, what an object of the class will consist of and
what operations can be performed on such an object.
Abstraction
Data abstraction refers to, providing only essential information to the outside world and hiding
their background details, i.e., to represent the needed information in program without presenting
the details.
For example, a database system hides certain details of how data is stored and created and
maintained. Similar way, C++ classes provides different methods to the outside world without
giving internal detail about those methods and data.
Encapsulation
Encapsulation is placing the data and the functions that work on that data in the same place. While
working with procedural languages, it is not always clear which functions work on which variables
but object-oriented programming provides you framework to place the data and the relevant
functions together in the same object.
Inheritance
One of the most useful aspects of object-oriented programming is code reusability. As the name
suggests Inheritance is the process of forming a new class from an existing class that is from the
existing class called as base class, new class is formed called as derived class.
This is a very important concept of object-oriented programming since this feature helps to reduce
the code size.
Polymorphism
The ability to use an operator or function in different ways in other words giving different
meaning or functions to the operators or functions is called polymorphism. Poly refers to many.
That is a single function or an operator functioning in many ways different upon the usage is called
polymorphism.
Abstraction
Data abstraction refers to, providing only essential information to the outside world and
hiding their background details, i.e., to represent the needed information in program without
presenting the details.
Data abstraction is a programming (and design) technique that relies on the separation of interface
and implementation.
Let's take one real life example of a TV, which you can turn on and off, change the channel, adjust
the volume, and add external components such as speakers, VCRs, and DVD players, BUT you do not
know its internal details, that is, you do not know how it receives signals over the air or through a
cable, how it translates them, and finally displays them on the screen.
22
Thus, we can say a television clearly separates its internal implementation from its external
interface and you can play with its interfaces like the power button, channel changer, and volume
control without having zero knowledge of its internals.
Now, if we talk in terms of C++ Programming, C++ classes provides great level of data abstraction.
They provide sufficient public methods to the outside world to play with the functionality of the
object and to manipulate object data, i.e., state without actually knowing how class has been
implemented internally.
For example, your program can make a call to the sort() function without knowing what algorithm
the function actually uses to sort the given values. In fact, the underlying implementation of the
sorting functionality could change between releases of the library, and as long as the interface stays
the same, your function call will still work.
In C++, we use classes to define our own abstract data types (ADT). You can use the coutobject of
class ostream to stream data to standard output like this:
int main( )
return 0;
Here, you don't need to understand how cout displays the text on the user's screen. You need to
only know the public interface and the underlying implementation of cout is free to change.
In C++, we use access labels to define the abstract interface to the class. A class may contain zero or
more access labels:
Members defined with a public label are accessible to all parts of the program. The data-abstraction
view of a type is defined by its public members.
Members defined with a private label are not accessible to code that uses the class. The private
sections hide the implementation from code that uses the type.
There are no restrictions on how often an access label may appear. Each access label specifies the
access level of the succeeding member definitions. The specified access level remains in effect until
the next access label is encountered or the closing right brace of the class body is seen.
23
- Class internals are protected from inadvertent user-level errors, which might corrupt the
state of the object.
- The class implementation may evolve over time in response to changing requirements or
bug reports without requiring change in user-level code.
By defining data members only in the private section of the class, the class author is free to make
changes in the data. If the implementation changes, only the class code needs to be examined to see
what affect the change may have. If data are public, then any function that directly accesses the data
members of the old representation might be broken.
Any C++ program where you implement a class with public and private members is an example of
data abstraction. Consider the following example:
class Adder{
public:
// constructor
Adder(int i = 0)
total = i;
total += number;
int getTotal()
return total;
};
private:
24
int total;
};
int main( )
Adder a;
a.addNum(10);
a.addNum(20);
a.addNum(30);
return 0;
When the above code is compiled and executed, it produces the following result:
Total 60
Above class adds numbers together, and returns the sum. The public
members addNumand getTotal are the interfaces to the outside world and a user needs to know
them to use the class. The private member total is something that the user doesn't need to know
about, but is needed for the class to operate properly.
Inheritance
When creating a class, instead of writing completely new data members and member functions,
the programmer can designate that the new class should inherit the members of an existing class.
This existing class is called the base class, and the new class is referred to as the derived class.
The idea of inheritance implements the is a relationship. For example, mammal IS-A animal, dog
IS-A mammal hence dog IS-A animal as well and so on.
25
A class can be derived from more than one classes, which means it can inherit data and functions
from multiple base classes. To define a derived class, we use a class derivation list to specify the
base class(es). A class derivation list names one or more base classes and has the form:
Where access-specifier is one of public, protected, or private, and base-class is the name of a
previously defined class. If the access-specifier is not used, then it is private by default.
We can summarize the different access types according to who can access them in the following
way:
A derived class inherits all base class methods with the following exceptions:
26
Overloaded operators of the base class.
When deriving a class from a base class, the base class may be inherited through public,
protected or private inheritance. The type of inheritance is specified by the access-specifier as
explained above.
We hardly use protected or private inheritance, but public inheritance is commonly used. While
using different type of inheritance, following rules are applied:
Public Inheritance: When deriving a class from a public base class, public members of the
base class become public members of the derived class and protected members of the base
class become protected members of the derived class. A base class's private members are
never accessible directly from a derived class, but can be accessed through calls to
the public and protected members of the base class.
Protected Inheritance: When deriving from a protected base class, public and
protected members of the base class become protected members of the derived class.
Private Inheritance: When deriving from a private base class, public and
protected members of the base class become private members of the derived class.
Types of Inheritance
1. Single Inheritance
2. Multiple Inheritance
3. Hierarchical Inheritance
4. Multilevel Inheritance
5. Hybrid Inheritance (also known as Virtual Inheritance)
Single Inheritance
In this type of inheritance one derived class inherits from only one base class. It is the most simplest
form of Inheritance.
27
Example:
Class A //base class
{
//class body
};
class B:public A //derived class
{
//class body
};
Multiple Inheritance
In this type of inheritance a single derived class may inherit from two or more than two base
classes.
28
Class A //1st base class
{
//class body
};
class B //2nd base class
{
//class body
};
//class body
};
Hierarchical Inheritance
In this type of inheritance, multiple derived classes inherits from a single base class.
29
Class A //base class
{
//class body
};
class B:public A //derived from class A
{
//class body
};
//class body
};
//class body
};
30
Multilevel Inheritance
In this type of inheritance the derived class inherits from a class, which in turn inherits from some
other class. The Super class for one, is sub class for the other.
//class body
};
//class body
};
31
Hybrid Inheritance
Hybrid Inheritance is combination of Hierarchical and Mutilevel Inheritance.
//class body
};
//class body
};
//class body
};
32
Constructors and Destructor Calls during Inheritance
- The compiler automatically call a base class constructor before executing the derived class
constructor.
- The compiler’s default action is to call the default constructor in the base class.
- If you want to specify which of several base class constructors should be called during the
creation of a derived class object.
- In these cases, you must explicitly specify which base class constructor should be called by
the compiler.
- This is done by specifying the arguments to the selected base class constructor in the
definition of the derived class constructor.
class Rectangle
{
private :
float length;
float width;
public:
Rectangle () //Default constructor
{
length = 0;
width = 0;
}
33
class Box : public Rectangle
{
private :
float height;
public:
Box () //default constructor
{
height = 0;
}
Box (float len, float wid, float ht) : Rectangle(len, wid) //calling constructor of parent class
{ explicitly
height = ht;
}
~BOX() //destructor
{
Cout<<”Derived Class Desrtuctor”;
}
float volume()
{
return area() * height;
}
};
int main ()
{
Box bx;
Box cx(4,8,5);
cout << bx.volume() << endl;
cout << cx.volume() << endl;
return 0;
}
Abstract Class
Abstract Class is a class which contains atleast one Pure Virtual function in it. Abstract
classes are used to provide an Interface for its sub classes. Classes inheriting an Abstract Class must
provide definition to the pure virtual function, otherwise they will also become abstract class.
1. Abstract class cannot be instantiated, but pointers and refrences of Abstract class type can be
created.
2. Abstract class can have normal functions and variables along with a pure virtual function.
3. Abstract classes are mainly used for Upcasting, so that its derived classes can use its interface.
4. Classes inheriting an Abstract Class must implement all pure virtual functions, or else they will
become Abstract too.
34
Pure Virtual Functions
Pure virtual Functions are virtual functions with no definition. They start with virtual keyword and
ends with “= 0” Here is the syntax for a pure virtual function,
When two or more classes are derived from a common base class, we can prevent multiple
copies of the base class being present in an object derived from those classes by declaring the base
class as virtual when it is being inherited. Such a base class is known as virtual base class. This can
be achieved by preceding the base class’ name with the word virtual. This type of situation
generally occurs during Hybrid Inheritance.
35
Consider following example:
In above example consider class A as Grandparent, class B and C as Parent and class D is a
child class.
Child class D will derive its Grandparent class A from two different Parent classes, class B
and class C this will create redundancy issue(Delicacy) which will result in an error, such problem
can be resolved using virtual base class method. Check following program for batter understanding:
class A
{
public:
int i;
};
36
int main()
{
D ob;
ob.i = 10; //unambiguous since only one copy of i is inherited.
ob.j = 20;
ob.k = 30;
ob.sum = ob.i + ob.j + ob.k;
cout << “Value of i is : ”<< ob.i<<”\n”;
cout << “Value of j is : ”<< ob.j<<”\n”; cout << “Value of k is :”<< ob.k<<”\n”;
cout << “Sum is : ”<< ob.sum <<”\n”;
return 0;
}
Containership in C++:
When a class contains objects of another class or its member. This kind of relationship is
called containership or nesting and the class which contains objects of another class as its
member is called as container class consider the following example for batter
understanding.
#include<iostream.h>
#include<conio.h>
class contained{
public:
int a,b;
void total()
cout<<"\n"<<a+b;
};
class container{
public:
void disp(){
37
c.a=40; //accessing properties using object of other class
c.b=50;
};
void main(){
clrscr();
con.b=59;
co.c.b=30;
co.disp();
getch();
38
Nested Class
A nested class is a class which is declared in another enclosing class. A nested class is a member and
as such has the same access rights as any other member. The members of an enclosing class have no
special access to members of a nested class; the usual access rules shall be obeyed.
#include <iostream.h>
class Nest
public:
private:
int s;
public:
{ s =a+b; }
void show( )
};
void main()
Nest::Display x;
x.sum(12, 10);
x.show();
39
Static Polymorphism
Static polymorphism involves binding of functions based on the number, type, and sequence
of arguments. The various types of parameters are specified in the function declaration, and
therefore the function can be bound to calls at compile time. This form of association is called early
binding. The term early binding stems from the fact that when the program is executed, the calls are
already bound to the appropriate functions.
C++ allows you to specify more than one definition for a function name or an operator in
the same scope, which is called function overloading and operator overloading respectively.
An overloaded declaration is a declaration that had been declared with the same name as a
previously declared declaration in the same scope, except that both declarations have different
arguments and obviously different definition (implementation).
When you call an overloaded function or operator, the compiler determines the most
appropriate definition to use by comparing the argument types you used to call the function or
operator with the parameter types specified in the definitions. The process of selecting the most
appropriate overloaded function or operator is called overload resolution.
Operator Overloading
Almost any operator can be overloaded in C++. However there are few operators which cannot be
overloaded. Operators that are not overloaded are follows
scope operator( :: ) =
sizeof =
member selector( . ) =
ternary operator(?:)=
40
Operator Overloading Syntax
1. Member Function
2. Non-Member Function
3. Friend Function
Operator overloading function can be a member function if the Left operand is an Object of that
class, but if the Left operand is different, then Operator overloading function must be a non-
member function.
Operator overloading function can be made friend function if it needs access to the private and
protected members of class.
2. Numbers of Operands cannot be changed. Unary operator remains unary, binary remains
binary etc.
4. Cannot redefine the meaning of a procedure. You cannot change how integers are added.
41
Overloading Arithmetic Operator
Arithmetic operators are most commonly used operator in C++. Almost all arithmetic operator can
be overloaded to perform arithmetic operation on user-defined data type. In the below example we
have overridden the + operator, to add to Time (hh:mm:ss) objects.
#include< iostream.h>
#include< conio.h>
class time
{
int h,m,s;
public:
time()
{
h=0, m=0; s=0;
}
void getTime();
void show()
{
cout<< h<< ":"<< m<< ":"<< s;
}
time operator+(time); //overloading '+' operator
};
time time::operator+(time t1) //operator function
{
time t;
int a,b;
a=s+t1.s;
t.s=a%60;
b=(a/60)+m+t1.m;
t.m=b%60;
t.h=(b/60)+h+t1.h;
t.h=t.h%12;
return t;
}
void time::getTime()
{
cout<<"\n Enter the hour(0-11) ";
cin>>h;
cout<<"\n Enter the minute(0-59) ";
cin>>m;
cout<<"\n Enter the second(0-59) ";
cin>>s;
}
void main()
{
clrscr();
time t1,t2,t3;
42
cout<<"\n Enter the first time ";
t1.getTime();
cout<<"\n Enter the second time ";
t2.getTime();
t3=t1+t2; //adding of two time object using '+' operator
cout<<"\n First time ";
t1.show();
cout<<"\n Second time ";
t2.show();
cout<<"\n Sum of times ";
t3.show();
getch();
}
Function overloading this operator must be a Non-Member function because left operand is not an
Object of the class.
You have seen above that << operator is overloaded with ostream class object cout to print
primitive type value output to the screen. Similarly you can overload << operator in your class to
print user-defined type to screen. For example we will overload << in time class to display time
object using cout.
time t1(3,15,48);
NOTE: When the operator does not modify its operands, the best way to overload the operator is
via friend function.
#include< iostream.h>
#include< conio.h>
class time
{
int hr,min,sec;
public:
time()
{
hr=0, min=0; sec=0;
}
43
time(int h,int m, int s)
{
hr=h, min=m; sec=s;
}
friend ostream& operator << (ostream &out, time &tm); //overloading '<<' operator
};
void main()
{
time tm(3,15,45);
cout << tm;
}
Output
Time is 3 hour : 15 min : 45 sec
You can also overload Relational operator like == , != , >= , <= etc. to compare two user-defined
object.
Example
class time
{
int hr,min,sec;
public:
time()
{
hr=0, min=0; sec=0;
}
44
t1.sec == t2.sec );
}
Assignment operator is used to copy the values from one object to another already existing object.
For example
Copy constructor is a special constructor that initializes a new object from an existing object.
Function Overloading
If any class have multiple functions with same names but different parameters then they are
said to be overloaded. Function overloading allows you to use the same name for different
functions, to perform, either same or different functions in the same class.
Function overloading is usually used to enhance the readability of the program. If you have to
perform one single operation but with different number or types of arguments, then you can simply
overload the function.
Ways to overload a function
45
int sum(int x, int y, int z)
{
cout << x+y+z;
}
Here sum() function is overloaded, to have two and three arguments. Which sum() function will
be called, depends on the number of arguments.
int main()
{
sum (10,20); // sum() with 2 parameter will be called
In this type of overloading we define two or more functions with same name and
same number of parameters, but the type of parameter is different. For example in this
program, we have two sum() function, first one gets two integer arguments and second one
gets two double arguments.
int main()
{
sum (10,20);
sum(10.5,20.5);
}
46
Note :
One of the key features of class inheritance is that a pointer to a derived class is type-compatible with
a pointer to its base class. Polymorphism is the art of taking advantage of this simple but powerful and
versatile feature.
For example, X is a base class and Y is a derived class. The pointer pointing to X can also point to Y.
Class X
{ //Class body };
Class Y : public X
{ //class body };
void main(){
X *ptr; //pointer to base class
X x;
Y y;
ptr = &x; // Pointing to base class
ptr = &y;//Pointing to Derived class using base class pointer
}
Dynamic Polymorphism
A function is said to exhibit dynamic polymorphism when it exists in more than one form,
and calls to its various forms are resolved dynamically when the program is executed. The
term late binding refers to the resolution of the functions at run-time instead of compile time. This
feature increases the flexibility of the program by allowing the appropriate method to be invoked,
depending on the context.
Overriding
If we inherit a class into the derived class and provide a definition for one of the base class's
function again inside the derived class, then that function is said to be overridden, and this
mechanism is called Function Overriding
1. Inheritance should be there. Function overriding cannot be done within a class. For this we
2. Function that is redefined must have exactly the same declaration in both base and derived
class, that means same name, same return type and same parameter list.
47
Function Call Binding with class Objects
Connecting the function call to the function body is called Binding. When it is done before the
program is run, its called Early Binding or Static Binding or Compile-time Binding.
Example:
class Base
{
public:
void shaow()
{
cout << "Base class\t";
}
};
class Derived:public Base
{
public:
void show()
{
cout << "Derived Class";
}
}
int mian()
{
Base b; //Base class object
Derived d; //Derived class object
b.show(); //Early Binding Ocuurs
d.show();
}
Output:
Base class Derived class
In the above example, we are calling the overrided function using Base class and Derived class
object. Base class object will call base version of the function and derived class's object will call the
derived version of the function.
when we use a Base class's pointer or reference to hold Derived class's object, then Function call
Binding gives some unexpected results.
class Base
{
public:
void shaow()
48
{
cout << "Base class";
}
};
class Derived:public Base
{
public:
void show()
{
cout << "Derived Class";
}
}
int mian()
{
Base* b; //Base class pointer
Derived d; //Derived class object
b = &d;
b->show(); //Early Binding Ocuurs
}
Output:
Base class
In the above example, although, the object is of Derived class, still Base class's method is called. This
happens due to Early Binding.
Compiler on seeing Base class's pointer, set call to Base class's show() function, without knowing
the actual object type.
Virtual Function
Virtual Function is a function in base class, which is overrided in the derived class, and which tells
the compiler to perform Late Binding on this function.
“Virtual” Keyword is used to make a member function of the base class Virtual.
class Base
{
public:
void show()
{
cout << "Base class";
}
49
};
class Derived:public Base
{
public:
void show()
{
cout << "Derived Class";
}
}
int main()
{
Base* b; //Base class pointer
Derived d; //Derived class object
b = &d;
b->show(); //Early Binding Ocuurs
}
Output:
Base class
When we use Base class's pointer to hold Derived class's object, base class pointer or reference
will always call the base version of the function
We can make base class's methods virtual by using virtual keyword while declaring them.
Virtual keyword will lead to Late Binding of that method.
class Base
{
public:
virtual void show()
{
cout << "Base class";
}
};
class Derived:public Base
{
public:
void show()
{
cout << "Derived Class";
}
}
int main()
{
50
Base* b; //Base class pointer
Derived d; //Derived class object
b = &d;
b->show(); //Late Binding Ocuurs
}
Output:
Derived class
On using Virtual keyword with Base class's function, Late Binding takes place and the derived
version of function will be called, because base class pointer pointes to Derived class object.
Important Points to Remember
1. Only the Base class Method's declaration needs the Virtual Keyword, not the definition.
2. If a function is declared as virtual in the base class, it will be virtual in all its derived classes.
A pure virtual function is a function that has the notation "= 0" in the declaration of that
function. Why we would want a pure virtual function and what a pure virtual function looks like is
explored in more detail below.
class SomeClass {
public:
virtual void pure_virtual() = 0; // a pure virtual function
// note that there is no function body
};
The "= 0" portion of a pure virtual function is also known as the pure specifier, because it’s what
makes a pure virtual function “pure”. Although the pure specifier appended to the end of the virtual
function definition may look like the function is being assigned a value of 0, that is not true. The
notation "= 0" is just there to indicate that the virtual function is a pure virtual function, and that
the function has no body or definition.
Any class that has at least one pure virtual function is called an abstract class. This means that
in our example above, the SomeClass class is an abstract class. An abstract class cannot have an
instance of itself created. So, using our example class from above, the following code would not
work:
51
This also means that any class that derives from an abstract class must override the definition
of the pure virtual function in the base class, and if it doesn’t then the derived class becomes an
abstract class as well.
Static polymorphism is considered more efficient and dynamic polymorphism more flexible.
Statically bound methods are those methods that are bound to their calls at compile time.
Dynamic function calls are bound to the functions during run-time. This involves the
additional step of searching the functions during run-time. On the other hand, no run-time
search is required for statically bound functions.
As applications are becoming larger and more complicated, the need for flexibility is
increasing rapidly. Most users have to periodically upgrade their software, and this could
become a very tedious task if static polymorphism is applied. This is because any change in
requirements requires a major modification in the code. In the case of dynamic binding, the
function calls are resolved at run-time, thereby giving the user the flexibility to alter the call
without having to modify the code.
Overriding of functions occurs when one class is inherited from another class. Overloading
can occur without inheritance.
Overloaded functions must differ in function signature ie either number of parameters or
type of parameters should differ. In overriding, function signatures must be same.
Overridden functions are in different scopes; whereas overloaded functions are in same
scope.
Overriding is needed when derived class function has to do some added or different job
than the base class function; whereas Overloading is used to have same name functions
which behave differently depending upon parameters passed to them.
52