Abstract Class in C++

In a C++ programming language, a class that contains at least one pure virtual function is called an abstract class.

This pure virtual function is declared within the base class and defined by a derived class.

An abstract class in C++ is a class that cannot be instantiated directly and contains one or more pure virtual functions. It is used as a base class for other classes to inherit from and must be subclassed and its pure virtual functions defined in order to be used.

Like another class, an abstract class can also contain normal functions.

Why Abstract class?

Abstract classes are used as a way to define a common interface or behavior that can be shared among multiple related classes.

By defining a set of pure virtual functions in the abstract class, it becomes a contract that any class that inherits from it must implement those functions, thus ensuring a consistent behavior across all of the derived classes.

Some common use cases for abstract classes include:

Creating a hierarchy of related classes that share some common functionality, but have unique behaviors as well.
Defining a base class for a group of classes that implement a certain interface or set of functions.
Enforcing a certain design pattern or structure in the code.
In addition, abstract classes can also be used to achieve polymorphism, which is the ability for objects of different types to be treated as if they were the same type.

This can be useful in situations where different objects need to be processed similarly but have different behaviors or implementations.

We can not create an object of an abstract class, Any attempt to do so will result in an error, but we can create a reference to an abstract class.  

Output

Description: In the above program, we have declared a pure virtual function “show()” in a base class A defined by derived class B. 

Because class A contains a pure virtual function therefore class A is an abstract class.  

An abstract class can also contain a normal member function (in this program member function is display() ).

Abstract Class Example in c++

In this example, the “Shape” class is abstract because it contains a pure virtual function called “draw” that has no implementation.

The three derived classes, “Circle”, “Triangle”, and “Rectangle”, inherit from “Shape” and implement the “draw” function with their own behavior.

When we create objects of these derived classes and call the “draw” function, it prints out a message indicating which shape is being drawn.

Animal Virtual class Example in C++

In this example, we have created five sub-classes that inherit from the “Animal” abstract class and implement the “speak” function with their own behavior.

When we create objects of these sub classes and call the “speak” function, each object prints out a message indicating the sound that the animal makes.

Categories C++