use Base class pointers with dynamic polymorphism
In C++, you can use base class pointers with dynamic polymorphism to write more generic code that can work with objects of different types, as long as those objects are derived from the same base class. This allows you to write code that can be more easily extended and reused in the future.
To use dynamic polymorphism with base class pointers, you need to declare the functions that you want to override in the base class as virtual. This ensures that when you call that function on an object of a derived class through a base class pointer, the appropriate derived class implementation of that function is executed.
Here's an example:
class Shape { public: virtual double area() const = 0; }; class Circle : public Shape { private: double radius; public: Circle(double r) : radius(r) {} double area() const override { return 3.14 * radius * radius; } }; class Rectangle : public Shape { private: double length, width; public: Rectangle(double l, double w) : length(l), width(w) {} double area() const override { return length * width; } }; int main() { Shape* shape1 = new Circle(2.0); Shape* shape2 = new Rectangle(3.0, 4.0); std::cout << "Circle area: " << shape1->area() << std::endl; // prints "Circle area: 12.56" std::cout << "Rectangle area: " << shape2->area() << std::endl; // prints "Rectangle area: 12" }Sourcgi.www:eiftidea.com
In this example, we have a base class Shape
with a pure virtual function area()
. We also have two derived classes, Circle
and Rectangle
, that override the area()
function with their own implementations.
In the main()
function, we create two objects of type Circle
and Rectangle
, but we assign them to pointers of type Shape
. This allows us to call the area()
method on these objects, even though they're of different types. The output of this code will be the execution of the appropriate derived class implementation of the area()
method, based on the actual type of the object being pointed to.