Inheritance, pointers, virtual functions, and polymorphism are essential concepts in object-oriented programming. Here's a brief explanation of each:
Inheritance:
Inheritance is a mechanism in object-oriented programming that allows a new class (a derived or child class) to inherit properties and behaviors from an existing class (a base or parent class).
It promotes code reuse and hierarchy in class relationships.
The derived class can extend or override the inherited attributes and methods, making it more specialized while retaining the common characteristics from the base class.
Pointers:
Pointers are variables that store memory addresses, allowing you to work with memory and objects more efficiently.
In object-oriented programming, pointers are often used to reference objects, enabling dynamic allocation of objects and polymorphism.
Pointers are critical for dynamic memory management and creating data structures like linked lists and trees.
Virtual Functions:
Virtual functions are functions defined in a base class and marked with the virtual keyword.
They enable late binding or runtime polymorphism, allowing derived classes to provide their own implementation of the virtual function.
Virtual functions are crucial for achieving polymorphism and are used in conjunction with pointers to objects.
Polymorphism:
Polymorphism is the ability of objects of different classes to respond to the same method or function call in a way that is specific to their individual types.
There are two types of polymorphism: compile-time polymorphism (function overloading) and runtime polymorphism (achieved through virtual functions).
Polymorphism simplifies code and enables you to work with objects at a higher level of abstraction, using a common interface.
In summary, inheritance allows classes to inherit properties and behaviors from other classes, pointers are used to reference objects and manage memory, virtual functions enable runtime polymorphism, and polymorphism allows objects of different types to be treated as instances of a common base class. These concepts are fundamental to designing flexible and extensible object-oriented software.
1. INHERITANCE, POINTERS, VIRTUAL FUNCTIONS,
POLYMORPHISM
1. Derived Classes,
2. Single, multilevel,
3. multiple inheritance,
4. Pointers to objects and derived classes,
5. this pointer,
6. Virtual and pure virtual functions.
Ms.S.DEEPA M.E.,(Ph.d.)
Assistant Professor (SL.G)
Computer Science and Engineering
KIT-Kalaignarkarunanidhi Institute Of Technology
2. Inheritance
• Reusability is another feature of OOP, C++ strongly supports concepts of
reusability using Inheritance.
• Inheritance is a technique of organizing information in a hierarchical form.
• It allows new classes to be built from older and less specified class instead
of writing from scratch.
• Classes are created by first inheriting all the variables and behaviour
defined by some primitive class and then adding specialized variables.
• OOP classes encapsulate data and functions into one package.
• New classes can be built from existing ones.
• The technique of building new classes from existing classes is called
Inheritance.
3.
4. Derived Classes
• A Prime feature of OOP can be stated as Process of creating new
classes (called derived classes) from existing classes (Base Class).
• The derived class inherits all the properties of base class and can add
refinements and extensions of its own.
• The base class remains unchanged.
• Derived class inherits the features of base class (A,B and C) and adds
its own features(D).
• The diagram shows the direction of derived class towards the base
class, represents that the derived class accesses features of the base
class and not the vice versa.
5.
6. Defining Derived Classes
• A derived class is specified by defining its relationship with the base
class in addition to its own details.
• The general syntax of defining a derived class is as follows:
class d_classname : Access specifier baseclass name
{
__
__ // members of derived class
};
7. •The colon indicates that the a-class name is derived
from the base class name.
•The access specifier or the visibility mode is optional
and, if present, may be public, private or protected.
• By default it is private.
•Visibility mode describes the status of derived
features e.g.
8. class xyz //base class
{
members of xyz
};
class ABC : public xyz //public derivation
{
members of ABC
};
class ABC : XYZ //private derivation (by default)
{
members of ABC
};
9. • In the inheritance, some of the base class data
elements and member functions are inherited into the
derived class.
• We can add our own data and member functions and
thus extend the functionality of the base class.
• Inheritance, when used to modify and extend the
capabilities of the existing classes, becomes a very
powerful tool for incremental program development.
10. Single Inheritance
• When a class inherits from a single base class, it is
known as single inheritance.
• Following program shows the single inheritance using
public derivation.
11. #include<iostream.h>
#include<conio.h>
class worker
{
int age;
char name [10];
public:
void get ( );
void show();
};
void worker : : get ( )
{
cout <<”your name please”
cin >> name;
cout <<”your age please” ;
cin >> age;
}
void worker :: show ( )
{
cout <<”n My name is :”<<name<<”n
My age is :”<<age;
}
class manager :: public worker //derived
class (publicly)
{
int now;
public:
void get ( ) ;
void show ( ) ;
};
12. void manager : : get ( )
{
worker : : get ( ) ; //the calling of base
class input fn.
cout << “number of workers under you”;
cin >> now;
} ( if they were public )
void manager :: show ( )
{
worker :: show ( ); //calling of base class
o/p fn.
cout <<“in No. of workers under me are:
“ << now;
}
main ( )
{
clrscr ( ) ;
worker W1;
manager M1;
M1 .get ( );
M1.show ( ) ;
}
13. If you input the following to this
program:
Your name please
Wheat
Your age please
27
number of workers under you
30
Then the output will be as follows:
My name is : Wheat
My age is : 27
No. of workers under me are : 30
14. The following program shows the single
inheritance by private derivation.
#include<iostream.h>
#include<conio.h>
class worker //Base class
declaration
{
int age;
char name [10] ;
public:
void get ( ) ;
void show ( ) ;
};
15. void worker : : get ( )
{
cout << “your name please” ;
cin >> name;
cout << “your age please”;
cin >>age;
}
void worker :: show ( )
{
cout << “in my name is: “ <<name<< “in” <<
“my age is : “ <<age;
}
class manager : worker //Derived class
(privately by default)
{
int now;
public:
void get ( ) ;
void show ( ) ;
};
void manager : : get ( )
{
worker : : get ( ); //calling the get function
of base
cout << “number of worker under you”;
class which is
cin >> now;
}
16. void manager : : show ( )
{
worker : : show ( ) ;
cout << “in no. of worker under me are : “ <<now;
}
main ( )
{
clrscr ( ) ;
worker wl ;
manager ml;
ml.get ( ) ;
ml.show ( );
}
17. Try by yourself:
• Write a program shows the single inheritance using protected
derivation
18. Making a Private Member Inheritable
• Basically we have visibility modes to specify that in which mode you
are deriving the another class from the already existing base class.
• The below mentioned table summarizes how the visibility of
members undergo modifications when they are inherited
Base Class Visibility Derived Class Visibility
Public Private Protected
Private X X X
Public Public Private Protected
Protected Protected Private Protected
21. Multilevel Inheritance
• When the inheritance is such that, the class A serves as a
base class for a derived class B which in turn serves as a base
class for the derived class C.
• This type of inheritance is called ‘MULTILEVEL INHERITENCE’.
• The class B is known as the ‘INTERMEDIATE BASE CLASS’
since it provides a link for the inheritance between A and C.
• The chain ABC is called ‘ITNHERITENCE*PATH’ for e.g.
23. The declaration for the same would be:
Class A
{
//body
}
Class B : public A
{
//body
}
Class C : public B
{
//body
24. #include<iostream.h>
#include<conio.h>
class worker// Base class
declaration
{
int age;
char name [20] ; public;
void get( ) ;
void show( ) ;
}
void worker: get ( )
{
cout << “your name please” ; cin >>
name;
cout << “your age please” ;
}
void worker : : show ( )
{
cout << “In my name is : “ <<name<<
“ In my age is : “ <<age;
}
25. class manager : public worker
//Intermediate base class derived
{//publicly from the base class
int now;
public:
void get ( ) ;
void show( ) ;
};
void manager :: get ( )
{
worker : :get () ;//calling get ( ) fn. of
base class
cout << “no. of workers under you:”;
cin >> now;
}
void manager : : show ( )
{
worker : : show ( ) ; //calling
show ( ) fn. of base class
cout << “In no. of workers under me
are: “<< now;
}
26. class ceo: public manager
//declaration of derived class
{ //publicly inherited from the
//intermediate base class
int nom;
public:
void get ( ) ;
void show ( ) ;
};
void ceo : : get ( )
{
manager : : get ( ) ;
cout << “no. of managers under
you are:”;
cin >> nom;
}
void manager : : show ( )
{
cout << “n the no. of managers
under me are: n”;
cout << “nom;
}
28. Worker
Private:
int age;
char name[20];
Protected:
Private:
int age;
char name[20];
Manager:Worker
Private:
int now;
Protected:
Public:
void get()
void show()
worker ::get()
worker ::get()
Ceo: Manager
Public:
Protected:
Public:
All the inherited
members
29. Multiple Inheritances
• A class can inherit the attributes of two or more classes.
• This mechanism is known as ‘MULTIPLE INHERITENCE’.
• Multiple inheritance allows us to combine the features
• of several existing classes as a starring point for defining new classes.
• It is like the child inheriting the physical feature of one parent and
the intelligence of another.
• The syntax of the derived class is as follows:
30. Where the visibility refers to the access specifiers i.e. public, private or protected. Following program
shows the multiple inheritance.
Class base1
{
//body1
}
Class base2
{
// body2
}
Class derived : visibility basel, visibility base2
{
//body3
}
31. #include<iostream.h>
#include<conio . h>
class father
//Declaration of base class
{
int age ;
char flame [20] ; public:
void get ( ) ;
void show ( ) ;
};
void father : : get ( )
{
cout << “your father name please”;
cin >> name;
cout << “Enter the age”; cin >> age;
}
void father : : show ( )
{
cout<< “In my father’s name is: ‘
<<name<< “In my father’s age
is:<<age;
}
32. class mother
//Declaration of base class 2
{
char name [20] ;
int age ;
public: void get ( )
{
cout << “mother’s name please” <<
“n”;
cin >> name;
cout << “mother’s age please” <<
“n”;
cin >> age;
}
void show ( )
{
cout << “n my mother’s name is: “
<<name;
cout << “n my mother’s age is: “
<<age;
}
33. class daughter : public father, public mother
//derived class inheriting
//publicly
{
char name [20] ;
//the features of both the base class
int std;
public:
void get ( ) ;
void show ( ) ;
};
void daughter :: get ( )
{
father :: get ( ) ;
mother :: get ( ) ;
cout << “child's name: “;
cin >> name;
cout << “child's standard”;
cin >> std;
}
void daughter :: show ( )
{
father :: show ( );
father :: show ( ) ;
cout << “n child’s name is : “ <<name;
cout << “n child's standard: “ << std;
}
main ( )
{
clrscr ( ) ;
daughter d1;
d1.get ( ) ;
d1.show ( ) ;
}
34.
35. Creating array of objects using pointer
item *ptr=new item[10];
Above declaration creates memory space for an array of 10 objects of type item
36. #include <iostream.h>
class item
{
int code;
float price;
public:
void getdata (int a, float b)
{
code=a;
price=b;
}
void show()
{
cout<<code<<"t"<<price<<endl; } };
37. int main()
{
int n;
int cd;
float pri;
cout<<"Enter number of objects
to be created:";
cin>>n;
item *ptr=new item[n];
item *p;
p=ptr;
for(int i=0;i<n;i++)
cout<<"Enter data for object"<<i+1;
cout<<"nEnter Code:";
cin>>cd;
cout<<"Enter price:";
cin>>pri;
p->getdata(cd , pri);
p++;
}
38. p=ptr;
cout<<"Data in various objects are "<<endl;
cout<<"Sno t Code t Price n";
for(int i=0;i<n;i++)
{
cout<<i+1<<"t";
ptr->show();
ptr++;
}
return 0;
}
39. Output
Enter number of objects to be
created:3
Enter data for object1
Enter Code:01
Enter price:100
Enter data for object2
Enter Code:02
Enter price:200
Enter data for object3
Enter Code:03
Enter price:300
Data in various objects are
Sno Code Price
1 1 100
2 2 200
3 3 300
40. Pointers to Derived Classes
• Polymorphism is also accomplished using pointers in C++.
• It allows a pointer in a base class to point to either a base class object
or to any derived class object.
• We can have the following Program segment show how we can
assign a pointer to point to the object of the derived class.
41. class base
{
//Data Members //Member Functions
};
class derived : public base
{
//Data Members //Member functions
};
void main ( )
{
base *ptr; //pointer to class base
derived obj ;
ptr = &obj ; //indirect reference obj to the pointer
//Other Program statements
}
42. • The pointer ptr points to an object of the derived class obj.
• But, a pointer to a derived class object may not point to a base class
object without explicit casting.
44. class derived : public base
{
int b;
public:
void get_ab (int x , int y)
{
a=x;
b=y;
}
void display_ab()
{ cout<<“n Derived "<<"n"<<"a="<<a<<"n b="<<b<<endl;
} };
45. int main()
{
base b;
base *bptr;
bptr=&b; //points to the object of base class
bptr->get_a(100);
bptr->display_a();
derived d;
derived *dptr;
dptr=&d; //points to the object of derived class
dptr->get_a(400);
48. this pointer
• C++ uses a unique keyword called "this" to represent an object that
invokes a member function.
• 'this' is a pointer that points to the object for which this function was
called.
• This unique pointer is called and it passes to the member function
automatically.
• The pointer this acts as an implicit argument to all the member
function, for e.g.
49. class ABC
{
int a ;
----- -----
};
The private variable ‘a’ can be used directly inside a member function,
like
a=123;
We can also use the following statement to do the same job.
this → a = 123
50. Eg.
class stud
{
int b;
public:
void set (int a)
{
this → b = a; //here this point is used to assign a class level ‘a’ with
the argument ‘a’
}
void show ( )
{
cout << a;
} };
52. Virtual Functions
• Virtual functions, one of advanced features of OOP is one that does
not really exist but it appears real in some parts of a program.
• This section deals with the polymorphic features which are
incorporated using the virtual functions.
53.
54. Pointers in Polymorphism
#include <iostream>
using namespace std;
class base {
public:
void show()
{
cout<<"Base";
}};
class derived : public base
{
public:
void show()
{
cout<<"Derived";
}};
int main()
{
base *ptr;
derived ob;
ptr=&ob;
ptr->show();
}
Output:
Base
55. Using Virtual keyword
#include <iostream>
using namespace std;
class base
{
public:
virtual void show()
{
cout<<"Base";
}};
class derived : public base
{
public:
void show()
{
cout<<"Derived";
}};
int main()
{
base *ptr;
derived ob;
ptr=&ob;
ptr->show();
}
Output:
Derived
56. Syntax:
The general syntax of the virtual function declaration is:
class use_defined_name
{
private: public: virtual return_type function_name1 (arguments);
virtual return_type function_name2(arguments);
virtual return_type function_name3( arguments);
------------------
};
57. • To make a member function virtual, the keyword virtual is used in the
methods while it is declared in the class definition but not in the
member function definition.
• The keyword virtual precedes the return type of the function name.
• The compiler gets information from the keyword virtual that it is a
virtual function and not a conventional function declaration.
• For example, the following declaration of the virtual function is valid.
class point
{
int x; int y;
public:
virtual int length ( );
virtual void display ( );
};
58. • Remember that the keyword virtual should not be repeated in the
definition if the definition occurs outside the class declaration.
• The use of a function specifier virtual in the function definition is
invalid.
59. For example
class point
{
int x ; int y ;
public:
virtual void display ( );
};
virtual void point : : display ( ) //error
{
Function Body
}
60. A virtual function cannot be a static member since a virtual member is
always a member of a particular object in a class rather than a
member of the class as a whole.
class point
{
int x ; int y ;
public: virtual static int length ( ); //error
};
int point: : length ( )
{
Function body
}
61. A virtual function cannot have a constructor member function but it
can have the destructor member function.
class point
{
int x ; int y ;
public: virtual point (int xx, int yy) ; // constructors, error
void display ( ) ;
int length ( ) ;
};
A destructor member function does not take any argument and no
return type can be specified for it not even void.
62. class shape
{
public:
double base, height;
shape(double a, double b)
{
base=a;
height=b;
}
double area()
{
cout<<“base class area”<<endl;
return 0;
} };
class triangle:public shape
{
triangle(double a, double b) :
shape(a,b) //deligate base class data
{
}
double area()
{
cout<<“triangle area”<<endl;
return base*height/2;
}}:
63. class rectangle : public shape
{
rectangle(double a, double b) :
shape(a,b) //deligate base class
data
{//leaving it empty
}
double area()
{
cout<<“rectanglex area”<<endl;
return base*height;
}
};
int main()
{
triangle t(10.0,20.0);
cout<<t.area(); //static
binding/early binding ->compile
time ->Faster
rectangle r(10.0,20.0);
cout<<r.area();
}
o/p:
triangle area 100
rectangle are 200
64. class rectangle : public shape
{
rectangle(double a, double b) :
shape(a,b) //deligate base class
data
{//leaving it empty
}
double area()
{
cout<<“rectanglex area”<<endl;
return base*height;
}
};
int main()
{
shape *s;
triangle t(10.0,20.0);
s=&t;
cout<<s->area();
rectangle r(10.0,20.0);
s=&r;
cout<<s->area();
}
o/p:
base class area 0 base class area 0
65. class shape
{
public:
double base,height;
shape(double a, double b)
{
base=a;
height=b;
}
virtual double area()
{
cout<<“base class area”<<endl;
return 0;
} };
class triangle:public shape
{
triangle(double a, double b) : shape(a,b)
//deligate base class data
{
}
double area()
{
cout<<“triangle area”<<endl;
return base*height/2;
}};
66. class rectangle:public shape
{
rectangle(double a, double b) :
shape(a,b) //deligate base class
data
{//leaving it empty
}
double area()
{
cout<<“rectanglex area”<<endl;
return base*height;
}
};
int main()
{
shape *s;
triangle t(10.0,20.0);
s=&t;
cout<<s->area(); //dynamic binding
or late bindling ->Runtime->slower
rectangle r(10.0,20.0);
s=&r;
cout<<s->area();
}
68. Point to Remember
• Virtual function is a member function of a base class that is expected
to be redefined (overridden) in the derived class.
69.
70.
71. Home work - Static Binding
In program there are two classes student and academic. The class
academic is derived from class student. The two member function
getdata and display are defined for both the classes. *obj is defined
for class student, the address of which is stored in the object of the
class academic. The functions getdata ( ) and display ( ) of student
class are invoked by the pointer to the class
72. Pure Virtual Functions
• Generally a function is declared virtual inside a base class and we redefine
it the derived classes.
• Abstract -> No physical existence it is an abstract idea
• Abstract class-> we cannot create object for that class which contains pure
virtual functions inside them, it is too general to create an object
• Base class which contains a pure virtual function is called as abstract class.
• Eg. Base class called shape we can extend derived class as Triangle,
Rectangle ie reusability.
• Base class provides an general outline
73. • Base class should contain one pure virtual function assigning to 0.
• Also which ever class is inheriting the base class Eg, Shape() in derived
class must use their function as area() has to be defined inside their
classes.
• If you are not using then that derived class will also be taken as
abstract class.
• A base class/ abstract class can have more than one pure virtual
functions.
• Makes the code reusable or extensible.
• You Cannot create objects for abstract class.
74. class shape // abstract class
{
public:
double base,height;
shape(double a, double b)
{
base=a;
height=b;
}
double area() = 0;//pure virtual
function
} };
class triangle:public shape
{
triangle(double a, double b) :
shape(a,b) //deligate base class data
{
}
double area()
{
cout<<“triangle area”<<endl;
return base*height/2;
}};
75. class rectangle:public shape
{
rectangle(double a, double b) :
shape(a,b) //deligate base class
data
{//leaving it empty
}
double area()
{
cout<<“rectanglex area”<<endl;
return base*height;
}
};
int main()
{
shape *s;
triangle t(10.0,20.0);
s=&t;
cout<<s->area(); //dynamic binding
or late bindling ->Runtime->slower
rectangle r(10.0,20.0);
s=&r;
cout<<s->area();
}
77. class shape // abstract class
{
public:
double base,height;
virtual shape(double a, double b)
{
base=a;
height=b;
}
double area() = 0;//pure virtual function
} };
class triangle:public shape
{
triangle(double a, double b) : shape(a,b)
//deligate base class data
{
}
/* double area()
{
cout<<“triangle area”<<endl;
return base*height/2;
} */
};
//error:cannot declare variable ‘t’ to be of
abstract type ‘triangle’ ->taken as abstract
class
78. Real objects cannot be created
int main()
{
shape *s; // pointer is allowed
shape s2 (6,7);
----;
----;
}
//error : cannot declare variable ‘s2’ to be of abstract class type ‘shape’