SlideShare a Scribd company logo
www.cppforschool.com
Polymorphism, Virtual Functions and Abstract Class
In C++, a pointer variable of a base class type can point to an object of its derived
class. There are situations when this feature of C++ can be used to develop generic
code for a variety of applications.
Pointer of base class
Consider the following program to understand pointer compatibility property
#include <iostream>
using namespace std;
class Shape
{
protected:
double width, height;
public:
void set_data (double a, double b)
{
width = a;
height = b;
}
};
class Rectangle: public Shape
{
public:
double area ()
{
return (width * height);
}
};
int main ()
{
Shape *sPtr; //declare pointer variables of type Shape
Rectangle Rect; //create the object rect of type Rectangle
sPtr = &Rect; //make sPtr point to the object rect.
sPtr->set_data (5,3); //set length and width of object rect
cout << sPtr -> area() << endl; //Compile Error !!
return 0;
}
Notice that even though rectPtr is pointing to rect (object of type Rectangle), when
the program executes, the statement sets length and width of rectangle. If you tried
to access area function of class Rectangle with sPtr it will give you compiler error.
sPtr -> area()
is a compiler error !
It means base class pointer can not access the additional member function of
its derived class. If we want to do this we need to type cast the base class pointer.
Using Type Casts with Base Class Pointers
We can use a type cast to get the compiler to accept the statement:
static_cast <Rectangle *> (sPtr)->area()
so we should write the statment
cout << static_cast <Rectangle *> (sPtr) -> area() << endl;
The type cast informs the compiler that sPtr is actually pointing to a Rectangle object
derived from the Shape base class. In general, a pointer to a base class that
actually points to a derived class object must first be appropriately cast
before the additional features of the derived class can be used.
Virtual Function and Polymorphism
Virtual functions are used in C++ to support polymorphic behavior. We are modifing
the above program and will introduce you the concept of virtual function by following
example:
#include <iostream>
using namespace std;
class Shape
{
protected:
double width, height;
public:
void set_data (double a, double b)
{
width = a;
height = b;
}
virtual double area()
{return 0;}
};
class Rectangle: public Shape
{
public:
double area ()
{
return (width * height);
}
};
int main ()
{
Shape *sPtr;
Rectangle Rect;
sPtr = &Rect;
sPtr -> set_data (5,3);
cout << sPtr -> area() << endl;
return 0;
}
Output :
15
A member of a class that can be redefined in its derived classes is known as a virtual
member. In order to declare a member of a class as virtual, we must precede its
declaration with the keyword virtual. The member function area() has been declared
as virtual in the base class because it is later redefined in each
derived class. The advantage of having virtual function is that we are able to
access area function of derived class by pointer variable of base class.
Pure Virtual Function and Abstract Class
In above example, base class Shape member function area do not need any
implementation because it is overriding in derived class. If this is the case, the C++
language permits the programmer to declare the function a pure virtual function. The
C++ way of declaring a pure virtual function is to put the expression = 0 in the class
declaration. For example, if a member function double area() is being declared pure
virtual, then its declaration in its class looks like
virtual double area() = 0;
A pure virtual function is sometimes called an abstract function, and a class with at
least one pure virtual function is called an abstract class. The C++ compiler will not
allow you to instantiate an abstract class. Abstract classes can only be subclassed:
that is, you can only use them as base classes from which to derive other classes.
A class derived from an abstract class inherits all functions in the base class, and will
itself be an abstract class unless it overrides all the abstract functions it inherits. The
usefulness of abstract classes lies in the fact that they define an interface that will
then have to be supported by objects of all classes derived from it.
#include <iostream>
using namespace std;
class Shape
{
protected:
double width, height;
public:
void set_data (double a, double b)
{
width = a;
height = b;
}
virtual double area() = 0;
};
class Rectangle: public Shape
{
public:
double area ()
{
return (width * height);
}
};
class Triangle: public Shape
{
public:
double area ()
{
return (width * height)/2;
}
};
int main ()
{
Shape *sPtr;
Rectangle Rect;
sPtr = &Rect;
sPtr -> set_data (5,3);
cout << "Area of Rectangle is " << sPtr -> area() << endl;
Triangle Tri;
sPtr = &Tri;
sPtr -> set_data (4,6);
cout << "Area of Triangle is " << sPtr -> area() << endl;
return 0;
}
Output :
Area of Rectangle is 15
Area of Triangle is 12
Ad

More Related Content

What's hot (20)

Constructor
ConstructorConstructor
Constructor
poonamchopra7975
 
Constructor and Destructors in C++
Constructor and Destructors in C++Constructor and Destructors in C++
Constructor and Destructors in C++
sandeep54552
 
C++: Constructor, Copy Constructor and Assignment operator
C++: Constructor, Copy Constructor and Assignment operatorC++: Constructor, Copy Constructor and Assignment operator
C++: Constructor, Copy Constructor and Assignment operator
Jussi Pohjolainen
 
constructors and destructors in c++
constructors and destructors in c++constructors and destructors in c++
constructors and destructors in c++
HalaiHansaika
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
farhan amjad
 
Constructors & destructors
Constructors & destructorsConstructors & destructors
Constructors & destructors
ForwardBlog Enewzletter
 
Virtual function in C++ Pure Virtual Function
Virtual function in C++ Pure Virtual Function Virtual function in C++ Pure Virtual Function
Virtual function in C++ Pure Virtual Function
Kamlesh Makvana
 
Tutconstructordes
TutconstructordesTutconstructordes
Tutconstructordes
Niti Arora
 
Constructor in c++
Constructor in c++Constructor in c++
Constructor in c++
Jay Patel
 
#OOP_D_ITS - 4th - C++ Oop And Class Structure
#OOP_D_ITS - 4th - C++ Oop And Class Structure#OOP_D_ITS - 4th - C++ Oop And Class Structure
#OOP_D_ITS - 4th - C++ Oop And Class Structure
Hadziq Fabroyir
 
C++ Multiple Inheritance
C++ Multiple InheritanceC++ Multiple Inheritance
C++ Multiple Inheritance
harshaltambe
 
Constructors and destructors
Constructors and destructorsConstructors and destructors
Constructors and destructors
Vineeta Garg
 
Constructors destructors
Constructors destructorsConstructors destructors
Constructors destructors
Pranali Chaudhari
 
Operator overloading in C++
Operator overloading in C++Operator overloading in C++
Operator overloading in C++
Ilio Catallo
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
Pranali Chaudhari
 
C++ Constructor destructor
C++ Constructor destructorC++ Constructor destructor
C++ Constructor destructor
Da Mystic Sadi
 
Constructor and Destructor
Constructor and DestructorConstructor and Destructor
Constructor and Destructor
Kamal Acharya
 
OO-like C Programming: Struct Inheritance and Virtual Function
OO-like C Programming: Struct Inheritance and Virtual FunctionOO-like C Programming: Struct Inheritance and Virtual Function
OO-like C Programming: Struct Inheritance and Virtual Function
Yu-Sheng (Yosen) Chen
 
classes & objects in cpp overview
classes & objects in cpp overviewclasses & objects in cpp overview
classes & objects in cpp overview
gourav kottawar
 
Virtual Functions
Virtual FunctionsVirtual Functions
Virtual Functions
Roman Okolovich
 
Constructor and Destructors in C++
Constructor and Destructors in C++Constructor and Destructors in C++
Constructor and Destructors in C++
sandeep54552
 
C++: Constructor, Copy Constructor and Assignment operator
C++: Constructor, Copy Constructor and Assignment operatorC++: Constructor, Copy Constructor and Assignment operator
C++: Constructor, Copy Constructor and Assignment operator
Jussi Pohjolainen
 
constructors and destructors in c++
constructors and destructors in c++constructors and destructors in c++
constructors and destructors in c++
HalaiHansaika
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
farhan amjad
 
Virtual function in C++ Pure Virtual Function
Virtual function in C++ Pure Virtual Function Virtual function in C++ Pure Virtual Function
Virtual function in C++ Pure Virtual Function
Kamlesh Makvana
 
Tutconstructordes
TutconstructordesTutconstructordes
Tutconstructordes
Niti Arora
 
Constructor in c++
Constructor in c++Constructor in c++
Constructor in c++
Jay Patel
 
#OOP_D_ITS - 4th - C++ Oop And Class Structure
#OOP_D_ITS - 4th - C++ Oop And Class Structure#OOP_D_ITS - 4th - C++ Oop And Class Structure
#OOP_D_ITS - 4th - C++ Oop And Class Structure
Hadziq Fabroyir
 
C++ Multiple Inheritance
C++ Multiple InheritanceC++ Multiple Inheritance
C++ Multiple Inheritance
harshaltambe
 
Constructors and destructors
Constructors and destructorsConstructors and destructors
Constructors and destructors
Vineeta Garg
 
Operator overloading in C++
Operator overloading in C++Operator overloading in C++
Operator overloading in C++
Ilio Catallo
 
C++ Constructor destructor
C++ Constructor destructorC++ Constructor destructor
C++ Constructor destructor
Da Mystic Sadi
 
Constructor and Destructor
Constructor and DestructorConstructor and Destructor
Constructor and Destructor
Kamal Acharya
 
OO-like C Programming: Struct Inheritance and Virtual Function
OO-like C Programming: Struct Inheritance and Virtual FunctionOO-like C Programming: Struct Inheritance and Virtual Function
OO-like C Programming: Struct Inheritance and Virtual Function
Yu-Sheng (Yosen) Chen
 
classes & objects in cpp overview
classes & objects in cpp overviewclasses & objects in cpp overview
classes & objects in cpp overview
gourav kottawar
 

Viewers also liked (12)

Inheritance
InheritanceInheritance
Inheritance
Aadhi Aadhithya
 
Inheritance : Extending Classes
Inheritance : Extending ClassesInheritance : Extending Classes
Inheritance : Extending Classes
Nilesh Dalvi
 
Inline function in C++
Inline function in C++Inline function in C++
Inline function in C++
Jenish Patel
 
Inline function in C++
Inline function in C++Inline function in C++
Inline function in C++
Learn By Watch
 
Class and object in C++
Class and object in C++Class and object in C++
Class and object in C++
rprajat007
 
friend function(c++)
friend function(c++)friend function(c++)
friend function(c++)
Ritika Sharma
 
C++ Function
C++ FunctionC++ Function
C++ Function
Hajar
 
operator overloading & type conversion in cpp over view || c++
operator overloading & type conversion in cpp over view || c++operator overloading & type conversion in cpp over view || c++
operator overloading & type conversion in cpp over view || c++
gourav kottawar
 
Inheritance in C++
Inheritance in C++Inheritance in C++
Inheritance in C++
Laxman Puri
 
Ntroduction to computer architecture and organization
Ntroduction to computer architecture and organizationNtroduction to computer architecture and organization
Ntroduction to computer architecture and organization
Fakulti seni, komputeran dan indusri kreatif
 
Pointer in C++
Pointer in C++Pointer in C++
Pointer in C++
Mauryasuraj98
 
pointers,virtual functions and polymorphism
pointers,virtual functions and polymorphismpointers,virtual functions and polymorphism
pointers,virtual functions and polymorphism
rattaj
 
Inheritance : Extending Classes
Inheritance : Extending ClassesInheritance : Extending Classes
Inheritance : Extending Classes
Nilesh Dalvi
 
Inline function in C++
Inline function in C++Inline function in C++
Inline function in C++
Jenish Patel
 
Inline function in C++
Inline function in C++Inline function in C++
Inline function in C++
Learn By Watch
 
Class and object in C++
Class and object in C++Class and object in C++
Class and object in C++
rprajat007
 
friend function(c++)
friend function(c++)friend function(c++)
friend function(c++)
Ritika Sharma
 
C++ Function
C++ FunctionC++ Function
C++ Function
Hajar
 
operator overloading & type conversion in cpp over view || c++
operator overloading & type conversion in cpp over view || c++operator overloading & type conversion in cpp over view || c++
operator overloading & type conversion in cpp over view || c++
gourav kottawar
 
Inheritance in C++
Inheritance in C++Inheritance in C++
Inheritance in C++
Laxman Puri
 
pointers,virtual functions and polymorphism
pointers,virtual functions and polymorphismpointers,virtual functions and polymorphism
pointers,virtual functions and polymorphism
rattaj
 
Ad

Similar to Chapter27 polymorphism-virtual-function-abstract-class (20)

Bc0037
Bc0037Bc0037
Bc0037
hayerpa
 
Chapter 2 OOP using C++ (Introduction).pptx
Chapter 2 OOP using C++ (Introduction).pptxChapter 2 OOP using C++ (Introduction).pptx
Chapter 2 OOP using C++ (Introduction).pptx
FiraolGadissa
 
Example for Abstract Class and Interface.pdf
Example for Abstract Class and Interface.pdfExample for Abstract Class and Interface.pdf
Example for Abstract Class and Interface.pdf
rajaratna4
 
Bca 2nd sem u-2 classes & objects
Bca 2nd sem u-2 classes & objectsBca 2nd sem u-2 classes & objects
Bca 2nd sem u-2 classes & objects
Rai University
 
Chapter 13 introduction to classes
Chapter 13 introduction to classesChapter 13 introduction to classes
Chapter 13 introduction to classes
rsnyder3601
 
OOC MODULE1.pptx
OOC MODULE1.pptxOOC MODULE1.pptx
OOC MODULE1.pptx
1HK19CS090MOHAMMEDSA
 
Mca 2nd sem u-2 classes & objects
Mca 2nd  sem u-2 classes & objectsMca 2nd  sem u-2 classes & objects
Mca 2nd sem u-2 classes & objects
Rai University
 
Basics of objective c
Basics of objective cBasics of objective c
Basics of objective c
sagaroceanic11
 
c++-language-1208539706757125-9.pdf
c++-language-1208539706757125-9.pdfc++-language-1208539706757125-9.pdf
c++-language-1208539706757125-9.pdf
nisarmca
 
05 Object Oriented Concept Presentation.pptx
05 Object Oriented Concept Presentation.pptx05 Object Oriented Concept Presentation.pptx
05 Object Oriented Concept Presentation.pptx
ToranSahu18
 
C++ language
C++ languageC++ language
C++ language
Hamza Asif
 
Ppt of c++ vs c#
Ppt of c++ vs c#Ppt of c++ vs c#
Ppt of c++ vs c#
shubhra chauhan
 
C++ Language
C++ LanguageC++ Language
C++ Language
Vidyacenter
 
polymorphism.ppt
polymorphism.pptpolymorphism.ppt
polymorphism.ppt
Shubham79233
 
Polymorphismupload
PolymorphismuploadPolymorphismupload
Polymorphismupload
Mukhtar_Hunzai
 
Class and object
Class and objectClass and object
Class and object
MushfiqurRahaman7
 
22 scheme OOPs with C++ BCS306B_module2.pdfmodule2.pdf
22 scheme  OOPs with C++ BCS306B_module2.pdfmodule2.pdf22 scheme  OOPs with C++ BCS306B_module2.pdfmodule2.pdf
22 scheme OOPs with C++ BCS306B_module2.pdfmodule2.pdf
sindhus795217
 
Synapseindia dot net development
Synapseindia dot net developmentSynapseindia dot net development
Synapseindia dot net development
Synapseindiappsdevelopment
 
Oops lecture 1
Oops lecture 1Oops lecture 1
Oops lecture 1
rehan16091997
 
麻省理工C++公开教学课程(二)
麻省理工C++公开教学课程(二)麻省理工C++公开教学课程(二)
麻省理工C++公开教学课程(二)
ProCharm
 
Chapter 2 OOP using C++ (Introduction).pptx
Chapter 2 OOP using C++ (Introduction).pptxChapter 2 OOP using C++ (Introduction).pptx
Chapter 2 OOP using C++ (Introduction).pptx
FiraolGadissa
 
Example for Abstract Class and Interface.pdf
Example for Abstract Class and Interface.pdfExample for Abstract Class and Interface.pdf
Example for Abstract Class and Interface.pdf
rajaratna4
 
Bca 2nd sem u-2 classes & objects
Bca 2nd sem u-2 classes & objectsBca 2nd sem u-2 classes & objects
Bca 2nd sem u-2 classes & objects
Rai University
 
Chapter 13 introduction to classes
Chapter 13 introduction to classesChapter 13 introduction to classes
Chapter 13 introduction to classes
rsnyder3601
 
Mca 2nd sem u-2 classes & objects
Mca 2nd  sem u-2 classes & objectsMca 2nd  sem u-2 classes & objects
Mca 2nd sem u-2 classes & objects
Rai University
 
c++-language-1208539706757125-9.pdf
c++-language-1208539706757125-9.pdfc++-language-1208539706757125-9.pdf
c++-language-1208539706757125-9.pdf
nisarmca
 
05 Object Oriented Concept Presentation.pptx
05 Object Oriented Concept Presentation.pptx05 Object Oriented Concept Presentation.pptx
05 Object Oriented Concept Presentation.pptx
ToranSahu18
 
22 scheme OOPs with C++ BCS306B_module2.pdfmodule2.pdf
22 scheme  OOPs with C++ BCS306B_module2.pdfmodule2.pdf22 scheme  OOPs with C++ BCS306B_module2.pdfmodule2.pdf
22 scheme OOPs with C++ BCS306B_module2.pdfmodule2.pdf
sindhus795217
 
麻省理工C++公开教学课程(二)
麻省理工C++公开教学课程(二)麻省理工C++公开教学课程(二)
麻省理工C++公开教学课程(二)
ProCharm
 
Ad

More from Deepak Singh (20)

Computer networks - CBSE New Syllabus (083) Class - XII
Computer networks - CBSE  New Syllabus (083) Class - XIIComputer networks - CBSE  New Syllabus (083) Class - XII
Computer networks - CBSE New Syllabus (083) Class - XII
Deepak Singh
 
Chpater29 operation-on-file
Chpater29 operation-on-fileChpater29 operation-on-file
Chpater29 operation-on-file
Deepak Singh
 
Chapter28 data-file-handling
Chapter28 data-file-handlingChapter28 data-file-handling
Chapter28 data-file-handling
Deepak Singh
 
Chapter26 inheritance-ii
Chapter26 inheritance-iiChapter26 inheritance-ii
Chapter26 inheritance-ii
Deepak Singh
 
Chapter25 inheritance-i
Chapter25 inheritance-iChapter25 inheritance-i
Chapter25 inheritance-i
Deepak Singh
 
Chapter24 operator-overloading
Chapter24 operator-overloadingChapter24 operator-overloading
Chapter24 operator-overloading
Deepak Singh
 
Chapter23 friend-function-friend-class
Chapter23 friend-function-friend-classChapter23 friend-function-friend-class
Chapter23 friend-function-friend-class
Deepak Singh
 
Chapter22 static-class-member-example
Chapter22 static-class-member-exampleChapter22 static-class-member-example
Chapter22 static-class-member-example
Deepak Singh
 
Chapter21 separate-header-and-implementation-files
Chapter21 separate-header-and-implementation-filesChapter21 separate-header-and-implementation-files
Chapter21 separate-header-and-implementation-files
Deepak Singh
 
Chapter20 class-example-program
Chapter20 class-example-programChapter20 class-example-program
Chapter20 class-example-program
Deepak Singh
 
Chapter19 constructor-and-destructor
Chapter19 constructor-and-destructorChapter19 constructor-and-destructor
Chapter19 constructor-and-destructor
Deepak Singh
 
Chapter18 class-and-objects
Chapter18 class-and-objectsChapter18 class-and-objects
Chapter18 class-and-objects
Deepak Singh
 
Chapter17 oop
Chapter17 oopChapter17 oop
Chapter17 oop
Deepak Singh
 
Chapter16 pointer
Chapter16 pointerChapter16 pointer
Chapter16 pointer
Deepak Singh
 
Chapter15 structure
Chapter15 structureChapter15 structure
Chapter15 structure
Deepak Singh
 
Chapter13 two-dimensional-array
Chapter13 two-dimensional-arrayChapter13 two-dimensional-array
Chapter13 two-dimensional-array
Deepak Singh
 
Chapter12 array-single-dimension
Chapter12 array-single-dimensionChapter12 array-single-dimension
Chapter12 array-single-dimension
Deepak Singh
 
Chapter 11 Function
Chapter 11 FunctionChapter 11 Function
Chapter 11 Function
Deepak Singh
 
Chapter 10 Library Function
Chapter 10 Library FunctionChapter 10 Library Function
Chapter 10 Library Function
Deepak Singh
 
Chapter 9 - Loops in C++
Chapter 9 - Loops in C++Chapter 9 - Loops in C++
Chapter 9 - Loops in C++
Deepak Singh
 
Computer networks - CBSE New Syllabus (083) Class - XII
Computer networks - CBSE  New Syllabus (083) Class - XIIComputer networks - CBSE  New Syllabus (083) Class - XII
Computer networks - CBSE New Syllabus (083) Class - XII
Deepak Singh
 
Chpater29 operation-on-file
Chpater29 operation-on-fileChpater29 operation-on-file
Chpater29 operation-on-file
Deepak Singh
 
Chapter28 data-file-handling
Chapter28 data-file-handlingChapter28 data-file-handling
Chapter28 data-file-handling
Deepak Singh
 
Chapter26 inheritance-ii
Chapter26 inheritance-iiChapter26 inheritance-ii
Chapter26 inheritance-ii
Deepak Singh
 
Chapter25 inheritance-i
Chapter25 inheritance-iChapter25 inheritance-i
Chapter25 inheritance-i
Deepak Singh
 
Chapter24 operator-overloading
Chapter24 operator-overloadingChapter24 operator-overloading
Chapter24 operator-overloading
Deepak Singh
 
Chapter23 friend-function-friend-class
Chapter23 friend-function-friend-classChapter23 friend-function-friend-class
Chapter23 friend-function-friend-class
Deepak Singh
 
Chapter22 static-class-member-example
Chapter22 static-class-member-exampleChapter22 static-class-member-example
Chapter22 static-class-member-example
Deepak Singh
 
Chapter21 separate-header-and-implementation-files
Chapter21 separate-header-and-implementation-filesChapter21 separate-header-and-implementation-files
Chapter21 separate-header-and-implementation-files
Deepak Singh
 
Chapter20 class-example-program
Chapter20 class-example-programChapter20 class-example-program
Chapter20 class-example-program
Deepak Singh
 
Chapter19 constructor-and-destructor
Chapter19 constructor-and-destructorChapter19 constructor-and-destructor
Chapter19 constructor-and-destructor
Deepak Singh
 
Chapter18 class-and-objects
Chapter18 class-and-objectsChapter18 class-and-objects
Chapter18 class-and-objects
Deepak Singh
 
Chapter15 structure
Chapter15 structureChapter15 structure
Chapter15 structure
Deepak Singh
 
Chapter13 two-dimensional-array
Chapter13 two-dimensional-arrayChapter13 two-dimensional-array
Chapter13 two-dimensional-array
Deepak Singh
 
Chapter12 array-single-dimension
Chapter12 array-single-dimensionChapter12 array-single-dimension
Chapter12 array-single-dimension
Deepak Singh
 
Chapter 11 Function
Chapter 11 FunctionChapter 11 Function
Chapter 11 Function
Deepak Singh
 
Chapter 10 Library Function
Chapter 10 Library FunctionChapter 10 Library Function
Chapter 10 Library Function
Deepak Singh
 
Chapter 9 - Loops in C++
Chapter 9 - Loops in C++Chapter 9 - Loops in C++
Chapter 9 - Loops in C++
Deepak Singh
 

Chapter27 polymorphism-virtual-function-abstract-class

  • 1. www.cppforschool.com Polymorphism, Virtual Functions and Abstract Class In C++, a pointer variable of a base class type can point to an object of its derived class. There are situations when this feature of C++ can be used to develop generic code for a variety of applications. Pointer of base class Consider the following program to understand pointer compatibility property #include <iostream> using namespace std; class Shape { protected: double width, height; public: void set_data (double a, double b) { width = a; height = b; } }; class Rectangle: public Shape { public: double area () { return (width * height); } }; int main () { Shape *sPtr; //declare pointer variables of type Shape Rectangle Rect; //create the object rect of type Rectangle sPtr = &Rect; //make sPtr point to the object rect. sPtr->set_data (5,3); //set length and width of object rect cout << sPtr -> area() << endl; //Compile Error !! return 0; }
  • 2. Notice that even though rectPtr is pointing to rect (object of type Rectangle), when the program executes, the statement sets length and width of rectangle. If you tried to access area function of class Rectangle with sPtr it will give you compiler error. sPtr -> area() is a compiler error ! It means base class pointer can not access the additional member function of its derived class. If we want to do this we need to type cast the base class pointer. Using Type Casts with Base Class Pointers We can use a type cast to get the compiler to accept the statement: static_cast <Rectangle *> (sPtr)->area() so we should write the statment cout << static_cast <Rectangle *> (sPtr) -> area() << endl; The type cast informs the compiler that sPtr is actually pointing to a Rectangle object derived from the Shape base class. In general, a pointer to a base class that actually points to a derived class object must first be appropriately cast before the additional features of the derived class can be used. Virtual Function and Polymorphism Virtual functions are used in C++ to support polymorphic behavior. We are modifing the above program and will introduce you the concept of virtual function by following example: #include <iostream> using namespace std; class Shape { protected: double width, height; public: void set_data (double a, double b) { width = a; height = b; } virtual double area() {return 0;}
  • 3. }; class Rectangle: public Shape { public: double area () { return (width * height); } }; int main () { Shape *sPtr; Rectangle Rect; sPtr = &Rect; sPtr -> set_data (5,3); cout << sPtr -> area() << endl; return 0; } Output : 15 A member of a class that can be redefined in its derived classes is known as a virtual member. In order to declare a member of a class as virtual, we must precede its declaration with the keyword virtual. The member function area() has been declared as virtual in the base class because it is later redefined in each derived class. The advantage of having virtual function is that we are able to access area function of derived class by pointer variable of base class. Pure Virtual Function and Abstract Class In above example, base class Shape member function area do not need any implementation because it is overriding in derived class. If this is the case, the C++ language permits the programmer to declare the function a pure virtual function. The C++ way of declaring a pure virtual function is to put the expression = 0 in the class declaration. For example, if a member function double area() is being declared pure virtual, then its declaration in its class looks like virtual double area() = 0;
  • 4. A pure virtual function is sometimes called an abstract function, and a class with at least one pure virtual function is called an abstract class. The C++ compiler will not allow you to instantiate an abstract class. Abstract classes can only be subclassed: that is, you can only use them as base classes from which to derive other classes. A class derived from an abstract class inherits all functions in the base class, and will itself be an abstract class unless it overrides all the abstract functions it inherits. The usefulness of abstract classes lies in the fact that they define an interface that will then have to be supported by objects of all classes derived from it. #include <iostream> using namespace std; class Shape { protected: double width, height; public: void set_data (double a, double b) { width = a; height = b; } virtual double area() = 0; }; class Rectangle: public Shape { public: double area () { return (width * height); } }; class Triangle: public Shape { public: double area () { return (width * height)/2; } }; int main () {
  • 5. Shape *sPtr; Rectangle Rect; sPtr = &Rect; sPtr -> set_data (5,3); cout << "Area of Rectangle is " << sPtr -> area() << endl; Triangle Tri; sPtr = &Tri; sPtr -> set_data (4,6); cout << "Area of Triangle is " << sPtr -> area() << endl; return 0; } Output : Area of Rectangle is 15 Area of Triangle is 12