In C, polymorphism is achieved through virtual functions and abstract base classes. Virtual functions allow base class functions to be overridden in derived classes, while abstract base classes contain pure virtual functions, forcing derived classes to provide implementations. This allows for polymorphic programming by using a base class pointer to access a derived class object and calling the appropriate method based on the object's actual type.
Polymorphism is the object-oriented programming (OOP) ), which allows objects to respond to the same message in different ways. In C, we use virtual functions and abstract base classes to achieve polymorphism.
Definition: Virtual function is a member function declared in the base class but implemented only in the derived class. When a virtual function is called through a base class pointer, the derived class's implementation is called.
Syntax:
class Base { public: virtual void print() const; }; class Derived : public Base { public: virtual void print() const override; };
override
The keyword indicates that we are overriding the virtual function of the base class.
Definition: An abstract base class is a base class that contains at least one pure virtual function. Pure virtual functions are not defined and are only implemented by derived classes.
Syntax:
class Base { public: virtual void f() const = 0; };
Consider a shape hierarchy where each shape class has a function that calculates its area area()
method.
Base class Shape:
class Shape { public: virtual double area() const = 0; };
Derived classes Circle and Rectangle:
class Circle : public Shape { public: Circle(double radius) : _radius(radius) {} double area() const override { return M_PI * _radius * _radius; } private: double _radius; }; class Rectangle : public Shape { public: Rectangle(double width, double height) : _width(width), _height(height) {} double area() const override { return _width * _height; } private: double _width, _height; };
Main function:
int main() { Shape* s1 = new Circle(5); Shape* s2 = new Rectangle(3, 4); std::cout << "Circle area: " << s1->area() << std::endl; std::cout << "Rectangle area: " << s2->area() << std::endl; return 0; }
Output:
Circle area: 78.5398 Rectangle area: 12
The above is the detailed content of C++ Virtual Functions and Abstract Base Classes: Exploring the Fundamentals of Polymorphic Programming. For more information, please follow other related articles on the PHP Chinese website!