Abstract Class in C++
Abstract class and Pure Virtual Function
Recall, a class in which a method cannot be implemented or a developer cannot provide definition. The object oriented language provide the concept of defining abstract method. The class having an abstract method is to be defined as an abstract class.
In C++, the abstract function is defined as a Pure Virtual Function. A class is a abstract class in C++ if it at least has one pure virtual function. Now in C++, the two-dimensional figure class is implemented as follows:
class TwoDFigure {
protected:
int d1;
int d2;
public:
TwoDFigure(int d1,int d2) {
this->d1 = d1;
this->d2 = d2;
}
//Pure Virtual Function
//abstract function as no definition
virtual void computeArea() = 0;
};
The abstract class can only be used by inheriting it. However, its object cannot be created i.e. cannot be instantiated. Recall, Inheritance represents a IS_A relationship. Therefore, a Triangle is a two-dimensional figure, a Rectangle is also a two-dimensional figure. The following code demonstrate how to use the abstract class.
class Rectangle : public TwoDFigure {
public:
Rectangle (int length,int breadth) : TwoDFigure(length,breadth)
{
}
//Override abstract function i.e. Pure Virtual Function
void computeArea() {
int area;
area = d1 * d2;
std::cout<<"Area of Rectangle "<area;
}
}
class Triangle : public TwoDFigure {
public:
Triangle (int base,int height) : TwoDFigure(base,height)
{
}
//Override abstract function i.e. Pure Virtual Function
void computeArea() {
double area;
area = (1.0/2.0) * d1 * d2;
std::cout<<"Area of Rectangle "<area;
}
}
Recall, in C++, the pointer to an object of the super class can refer to the objects of the sub classes and then it calls the method of that sub class. It is used to achieve runtime polymorphism.
The Rectangle and the Triangle class can be tested by defining a class with the main method as follows:
int main() {
// Pointer to object of TwoDFigure class
// Can refer to objects of TwoDFigure
TwoDFigure *figure;
figure = new Rectangle(10,20);
figure->computeArea();//version of Rectangle class
figure = new Triangle(10,20);
figure->computeArea();//version of Triangle class
return 0;
}
The abstract(defined as Pure Virtual Function) method is a unimplemented method in an abstract class. It is provided implementation in the respective sub classes. It archives runtime Polymorphism.
Imagine the cut-copy and the paste operation in software. Their implementation varies from one software to another software.
Abstract Class in C++
Reviewed by Syed Hafiz Choudhary
on
September 14, 2023
Rating:
![](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhjeos7brAHyt61uYl5dnwsymjWgUJ-USdOmMmEasQFo31abglU6gGwco6ExHzUVTbi0sA0RLl9PmURytvLe0RTD5BrHKujkVfE3ivHfL6Wb9hCOeJsjvF0BoSDGdTQXqloSejdXZsOfZ7zA-xT9GFBUAUszB99YbeBIhpfUnwysgC1iiImwNsw2hS2Swqb/s72-c/abstract-class-in-cplus.png)
No comments: