In C++, abstract classes are used to accomplish abstraction. Abstraction is the process of hiding internal details and displaying only functionality in C++. There are two approaches to create abstraction:
- Interfaces
- Abstract Class
Both the abstract class and the interface can have abstract methods, which are required for abstraction.
Abstract Class:
In C++, a class is abstracted by declaring at least one of its functions to be pure virtual. In the declaration of a pure virtual function, the keyword “= 0” is used. Derived classes must provide the implementation.
Let’s look at an abstract class in C++ that has only one abstract method: draw (). Rectangle and Circle are two derived classes that implement it. Both classes are implemented differently.
#include <iostream> using namespace std; class Shape { public: virtual void draw()=0; }; class Rectangle : Shape { public: void draw() { cout < <"drawing rectangle..." < <endl; } }; class Square : Shape { public: void draw() { cout <<"drawing square..." < <endl; } }; int main( ) { Rectangle rec; Square cir; rec.draw(); cir.draw(); return 0; }
Output:
drawing rectangle...
drawing square...
Join Our Community
Join our WhatsApp Group To know more about Programming Language tips, tricks and knowledge about and how to start learning any programming language.