Pointers are often used in C++ to achieve polymorphism. When a function is declared as virtual, it enables dynamic binding, which means that the appropriate function to call is determined at runtime based on the type of the object pointed to by the pointer.
In other words, when a pointer of the base class type points to an object of the derived class, and the function is called using the pointer, the function in the derived class is executed rather than the function in the base class. This is an important aspect of polymorphism in C++, and it allows for the creation of flexible and extensible code.
#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;
Sec *Ptr1 = &Object;
Ptr1->printing();
Third Object_2;
Third *Ptr2 = &Object_2;
Ptr2->printing();
return 0;
}
This C++ code defines three classes: Prim
, Sec
, and Third
. The Prim
class has a virtual function printing()
defined. The Sec
and Third
classes inherit from Prim
and override the printing()
function.
In the main()
function, an object of the Sec
class is created and a pointer Ptr1
of type Sec
is initialized to point to the Object
object. The Ptr1->printing()
statement calls the printing()
function on the object pointed to by Ptr1
. Since the printing()
function is virtual and has been overridden in the Sec
class, the printing()
function in the Sec
class is called and the output is "I am From Sec Cls".
Then, an object of the Third
class is created and a pointer Ptr2
of type Third
is initialized to point to the Object_2
object. The Ptr2->printing()
statement calls the printing()
function on the object pointed to by Ptr2
. Again, since the printing()
function is virtual and has been overridden in the Third
class, the printing()
function in the Third
class is called and the output is "I am from Third Cls".
No comments:
Post a Comment