C++ - Polymorphism
If there are multiple classes (rectangle, circle) derived from common base class (shape), polymorphism provides the ability to call the methods in derived classes (rectangle, circle) using the base class (shape) pointers.
To understand the poymorphism, you need to know about the virtual functions and inheritance. Inheritance means classes can be derived from another class called base class. Derived classes will have all the features of the base class and it will have access to base class protected and public members. Derived classes will not have access to private members of the base class.
Regarding Virtual Functions - In C++, you need to use the virutal keyword in both base and derived classes. In C#, you need to use virual keyword in base case and override keyword in derived classes. In Java you do not need to use any keyword like virtual or override since by default all non static functions are considered as virual. You have to make it either private or use final keyword to remove the default virtual feature in each function in the Java classes.
When writing derived classes C++ and C# uses ":" between derived class and base class. Java uses extends keyword instead of :
There are four classes given on this example. Shape is a base class and Rect1, Circle and Triangle are the classes derived from the base class Shape. The base class Shape* is used to access all three dervied class functions. It is called Polymorphism.
Useful links:
Source Code
class Shape
{
public:
Shape()
{
std::cout << "Calling Shape Constructor\n";
}
virtual ~Shape()
{
std::cout << "Calling Shape Destructor\n\n";
}
virtual void draw() = 0; // // Pure Virtual Function
virtual void display() { };
};
class Rect1 : public Shape
{
int l,b;
public:
virtual ~Rect1()
{
std::cout << "Calling Rectangle Destructor\n";
}
Rect1()
{
std::cout << "Calling Rectangle Constructor\n\n";
}
virtual void draw() {}
virtual void display() { };
};
class Circle : public Shape
{
int r;
public:
virtual ~Circle()
{
std::cout << "Calling Circle Destructor\n";
}
Circle()
{
std::cout << "Calling Circle Constructor\n\n";
}
virtual void draw() {};
virtual void display() { };
};
class Triangle : public Shape
{
int a,b,c;
public:
virtual ~Triangle()
{
std::cout << "Calling Triangle Destructor\n";
};
Triangle()
{
std::cout << "Calling Triangle Constructor\n\n";
}
virtual void draw() {};
virtual void display() { };
};
int _tmain(int argc, _TCHAR* argv[])
{
Shape *p[] = {
new Rect1(),
new Circle(),
new Triangle(),
};
for(int i = 0; i < sizeof(p) / sizeof(p[0]); i++)
p[i]->draw();
for(int i = 0; i < sizeof(p) / sizeof(p[0]); i++)
delete p[i];
return 0;
}
Output
Calling Shape Constructor
Calling Rectangle Constructor
Calling Shape Constructor
Calling Circle Constructor
Calling Shape Constructor
Calling Triangle Constructor
Calling Rectangle Destructor
Calling Shape Destructor
Calling Circle Destructor
Calling Shape Destructor
Calling Triangle Destructor
Calling Shape Destructor
|