Home > Article > Backend Development > How to declare and call virtual functions in C++?
Virtual function is a polymorphism mechanism that allows a derived class to override the member function of its base class: Declaration: Add the keyword virtual before the function name. Call: Using a base class pointer or reference, the compiler will dynamically bind to the appropriate implementation of the derived class. Practical case: By defining the base class Shape and its derived classes Rectangle and Circle, the application of virtual functions in polymorphism is demonstrated to calculate area and draw shapes.
Virtual function in C
Virtual function is a polymorphism mechanism that allows a derived class to override the properties of its base class Member functions. This enables programmers to define common behavior in a base class while still allowing derived classes to provide its instance-specific implementation of that behavior.
Declaring virtual functions
To declare a virtual function, place the keyword virtual
at the beginning of the function name. For example:
class Base { public: virtual void print() const; };
Call virtual function
Call virtual function, use base class pointer or reference. The compiler will dynamically bind to the appropriate implementation of the derived class. For example:
void doSomething(Base* base) { base->print(); }
Practical case
The following is an example of using virtual functions:
#include <iostream> class Shape { public: virtual double area() const = 0; virtual void draw() const = 0; }; class Rectangle : public Shape { public: Rectangle(double width, double height) : width_(width), height_(height) {} double area() const override { return width_ * height_; } void draw() const override { std::cout << "Drawing rectangle" << std::endl; } private: double width_; double height_; }; class Circle : public Shape { public: Circle(double radius) : radius_(radius) {} double area() const override { return 3.14 * radius_ * radius_; } void draw() const override { std::cout << "Drawing circle" << std::endl; } private: double radius_; }; int main() { Shape* rectangle = new Rectangle(5, 10); Shape* circle = new Circle(5); std::cout << rectangle->area() << std::endl; // Output: 50 std::cout << circle->area() << std::endl; // Output: 78.5 rectangle->draw(); // Output: Drawing rectangle circle->draw(); // Output: Drawing circle return 0; }
The above is the detailed content of How to declare and call virtual functions in C++?. For more information, please follow other related articles on the PHP Chinese website!