SlideShare a Scribd company logo
1 of 79
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
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.
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.
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
};
•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.
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
};
• 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.
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.
#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 ( ) ;
};
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 ( ) ;
}
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
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 ( ) ;
};
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;
}
void manager : : show ( )
{
worker : : show ( ) ;
cout << “in no. of worker under me are : “ <<now;
}
main ( )
{
clrscr ( ) ;
worker wl ;
manager ml;
ml.get ( ) ;
ml.show ( );
}
Try by yourself:
• Write a program shows the single inheritance using protected
derivation
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
Effect of inheritance on visibility of members
Access mechanism in classes
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.
Base class
Inheritance path Intermediate base
class
Derived class
A
B
C
The declaration for the same would be:
Class A
{
//body
}
Class B : public A
{
//body
}
Class C : public B
{
//body
#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;
}
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;
}
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;
}
main ( )
{
clrscr ( ) ;
ceo cl ;
cl.get ( ) ;
cout << “nn”;
cl.show ( ) ;
}
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
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:
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
}
#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;
}
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;
}
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 ( ) ;
}
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
#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; } };
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++;
}
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;
}
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
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.
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
}
• 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.
#include <iostream.h>
class base
{
public:
int a;
void get_a (int x)
{
a=x;
}
void display_a ()
{
cout<<“n base"<<"n"<<"a="<<a<<endl;
}};
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;
} };
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);
dptr->display_a();
dptr->get_ab(300,200);
dptr->display_ab();
bptr=&d; //points to the object of derived class
bptr->get_a(400);
bptr->display_a();
return 0;
}
Output:
In base a=100
In base a=400
In Derived a=300 b=200
In base a=400
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.
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
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;
} };
main ( )
{
stud S1, S2;
S1.set (5) ;
S2.show ( );
}
o/p = 5
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.
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
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
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);
------------------
};
• 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 ( );
};
• 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.
For example
class point
{
int x ; int y ;
public:
virtual void display ( );
};
virtual void point : : display ( ) //error
{
Function Body
}
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
}
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.
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;
}}:
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
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
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;
}};
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();
}
Output:
Triangle area 100
Rectangle area 200
Point to Remember
• Virtual function is a member function of a base class that is expected
to be redefined (overridden) in the derived class.
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
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
• 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.
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;
}};
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();
}
Output:
triangle area 100
triangle area 100
rectangle area 200
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
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’
Thank you!

More Related Content

Similar to INHERITANCE, POINTERS, VIRTUAL FUNCTIONS, POLYMORPHISM

Similar to INHERITANCE, POINTERS, VIRTUAL FUNCTIONS, POLYMORPHISM (20)

Inheritance
InheritanceInheritance
Inheritance
 
OOPS IN C++
OOPS IN C++OOPS IN C++
OOPS IN C++
 
29c
29c29c
29c
 
29csharp
29csharp29csharp
29csharp
 
11 Inheritance.ppt
11 Inheritance.ppt11 Inheritance.ppt
11 Inheritance.ppt
 
Inheritance in C++
Inheritance in C++Inheritance in C++
Inheritance in C++
 
inheriTANCE IN OBJECT ORIENTED PROGRAM.pptx
inheriTANCE IN OBJECT ORIENTED PROGRAM.pptxinheriTANCE IN OBJECT ORIENTED PROGRAM.pptx
inheriTANCE IN OBJECT ORIENTED PROGRAM.pptx
 
02-OOP with Java.ppt
02-OOP with Java.ppt02-OOP with Java.ppt
02-OOP with Java.ppt
 
C++ presentation
C++ presentationC++ presentation
C++ presentation
 
OOP
OOPOOP
OOP
 
Lecturespecial
LecturespecialLecturespecial
Lecturespecial
 
Java oops PPT
Java oops PPTJava oops PPT
Java oops PPT
 
Inheritance
InheritanceInheritance
Inheritance
 
Inheritance
InheritanceInheritance
Inheritance
 
Ppt of c++ vs c#
Ppt of c++ vs c#Ppt of c++ vs c#
Ppt of c++ vs c#
 
Constructor&method
Constructor&methodConstructor&method
Constructor&method
 
Introduction to object oriented programming concepts
Introduction to object oriented programming conceptsIntroduction to object oriented programming concepts
Introduction to object oriented programming concepts
 
Inheritance
InheritanceInheritance
Inheritance
 
Inheritance
InheritanceInheritance
Inheritance
 
lecture 6.pdf
lecture 6.pdflecture 6.pdf
lecture 6.pdf
 

Recently uploaded

Processing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxProcessing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxpranjaldaimarysona
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Dr.Costas Sachpazis
 
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVRajaP95
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxJoão Esperancinha
 
GDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSCAESB
 
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...Soham Mondal
 
High Profile Call Girls Nashik Megha 7001305949 Independent Escort Service Na...
High Profile Call Girls Nashik Megha 7001305949 Independent Escort Service Na...High Profile Call Girls Nashik Megha 7001305949 Independent Escort Service Na...
High Profile Call Girls Nashik Megha 7001305949 Independent Escort Service Na...Call Girls in Nagpur High Profile
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCall Girls in Nagpur High Profile
 
Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxpurnimasatapathy1234
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024hassan khalil
 
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130Suhani Kapoor
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile servicerehmti665
 
Porous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingPorous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingrakeshbaidya232001
 
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSHARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSRajkumarAkumalla
 

Recently uploaded (20)

Processing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxProcessing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptx
 
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
 
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
 
GDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentation
 
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
 
High Profile Call Girls Nashik Megha 7001305949 Independent Escort Service Na...
High Profile Call Girls Nashik Megha 7001305949 Independent Escort Service Na...High Profile Call Girls Nashik Megha 7001305949 Independent Escort Service Na...
High Profile Call Girls Nashik Megha 7001305949 Independent Escort Service Na...
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
 
Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptx
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024
 
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
 
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile service
 
Porous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingPorous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writing
 
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSHARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
 
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCRCall Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
 
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptxExploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
 

INHERITANCE, POINTERS, VIRTUAL FUNCTIONS, POLYMORPHISM

  • 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
  • 19. Effect of inheritance on visibility of members
  • 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.
  • 22. Base class Inheritance path Intermediate base class Derived class A B C
  • 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; }
  • 27. main ( ) { clrscr ( ) ; ceo cl ; cl.get ( ) ; cout << “nn”; cl.show ( ) ; }
  • 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.
  • 43. #include <iostream.h> class base { public: int a; void get_a (int x) { a=x; } void display_a () { cout<<“n base"<<"n"<<"a="<<a<<endl; }};
  • 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);
  • 46. dptr->display_a(); dptr->get_ab(300,200); dptr->display_ab(); bptr=&d; //points to the object of derived class bptr->get_a(400); bptr->display_a(); return 0; }
  • 47. Output: In base a=100 In base a=400 In Derived a=300 b=200 In base 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; } };
  • 51. main ( ) { stud S1, S2; S1.set (5) ; S2.show ( ); } o/p = 5
  • 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(); }
  • 76. Output: triangle area 100 triangle area 100 rectangle area 200
  • 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’