Polymorphism in C++ is the ability of objects of different classes to be treated as if they are objects of the same class. In C++, polymorphism can be achieved through inheritance and virtual functions.
Polymorphism through inheritance is achieved by creating a derived class that inherits from a base class. The derived class can override the methods of the base class with its own implementation, and objects of the derived class can be treated as objects of the base class.
Polymorphism through virtual functions is achieved by declaring a function in the base class as virtual, which allows derived classes to provide their own implementation of the function. When a virtual function is called on an object, the appropriate implementation of the function is selected based on the type of the object at runtime, rather than the type of the variable used to refer to the object.
Polymorphism allows for more flexible and reusable code, as objects of different classes that share a common base class can be treated in the same way. This can simplify program design and make code easier to maintain and extend.
A virtual function is a function that is declared in a base class and can be overridden in a derived class. When a virtual function is called on an object, the appropriate implementation of the function is selected based on the type of the object at runtime, rather than the type of the variable used to refer to the object.
To declare a virtual function, the virtual
keyword is used before the function declaration in the base class.
#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() {
Sec Object;
Object.printing();
Third Object_2;
Object_2.printing();
return 0;
}
This C++ code defines three classes: Prim
, Sec
, and Third
. Prim
is the base class, and Sec
and Third
are derived classes that inherit from Prim
. The Prim
class has a virtual function called printing()
that does not have any implementation, and Sec
and Third
both override the printing()
function with their own implementations.
In the main()
function, two objects are created, one of type Sec
and one of type Third
, and their printing()
methods are called. Since the printing()
method is declared as virtual in the base class Prim
, the appropriate implementation of the function is selected based on the type of the object at runtime.
No comments:
Post a Comment