Table of Contents
Abstract class in C++ language
In this tutorial, we will discuss the Oop concept of Abstract class in C++ language
An abstract class in C++ language, which is a class contain pure one or more(at least one) virtual function in a base class . A pure virtual function is a virtual member function, that noticeable as having no any implementation.
Virtual function
virtual void functionName()=0;
virtual void sayHollow()=0;
Some important points about abstract class
- An abstract class must have at least one pure virtual(it can have one or more virtual function) function and it can have normal functions and variables.
- Abstract classes are mainly used to inherit properties or attributes to derived class so that its derived classes can use their interface.
- Classes inheriting an abstract class must implement all pure virtual functions or otherwise, they will become abstract too.
- We can’t declare an object of abstract class because it has partoal implementation of the method. When we create an object of abstract class, an error message would be displayed.
Example of abstract class in C++
class class_Name { public: //A pure virtual function is specified by placing "= 0" in its declaration as follows virtual display()=0; //pure virtual function //it has no definition }
Explanation of abstraction in C++
Example given below
Example 1
class shape{//class ahape has a vertual function virtual void draw()=0; //virtual function with no implementation } class circle{ //derived (1) class circle void draw(){ // implementation of draw() function } class rectangle{ //derived (2) class rectangle void draw(){ // implementation of draw() function } class square{ //derived (2) class squair void draw(){ // implementation of draw() function }
At the above example, shape is a base class. Draw() is a virtual function is inside the shape( base) class which has no implementation, but it is only definition. So class shape is a abstract class. function draw() is a pure virtual function.
Every derived class having implementation of draw() method
facts
A class is abstract if it has at least one pure virtual function
Program 1
When the above code is executed, It produces the following result
this is teacher class this is principal class this is school clark class End the program
Example
Abstraction in Cpp using pointer
Program 2
When the above code is executed, It produces the following result
This is first derived class This is second derived class End the program
Related Links
Encapsulation in C++ Encapsulation in Java
Polymorphism in C++ Methodoverriding in Java
Method overloading in java Constructor overloading in Java
Exception Handling in Java Abstract class in Java
Method over riding in Python