The purpose of an abstract class is to define a common interface for a set of related classes.
The derived classes must implement the pure virtual function(s) of the abstract class in order to be instantiated.
This way, an abstract class can provide a common functionality that all the derived classes must have, while allowing each derived class to implement its own specific behavior.
#include <iostream>
using namespace std;
class Prim{
public:
virtual void printing() {}
};
class Sec : public Prim{
public:
void printing() {
cout << "I am From Sec Cls" << endl;
}
};
class Third : public Prim {
public:
void printing() {
cout << "I am from Third Cls" << endl;
}
};
int main() {
Prim Object;
Object.printing();
return 0;
}
In this C++ code, we have defined a class hierarchy with a base class Prim
and two derived classes Sec
and Third
. The base class Prim
has a virtual function printing()
, which is overridden in both derived classes.
In the main()
function, an object of the base class Prim
is created and its printing()
function is called. Since the printing()
function is virtual and has been defined in the base class with an empty definition, it will call the base class's implementation. Therefore, the output will be an empty line.
Note that the Prim
class is an abstract class, as its virtual function printing()
has an empty definition, and hence it cannot be instantiated. We can only create objects of the derived classes, which have overridden the virtual function.
No comments:
Post a Comment