Home  >  Article  >  Backend Development  >  How to override base class function in C++?

How to override base class function in C++?

王林
王林Original
2024-04-12 22:45:02422browse

In C, function overriding allows a derived class to override a base class function to extend or modify its behavior. The syntax is: Have the same function name Have the same function signature Use the override keyword

C++ 中如何覆盖基类函数?

Comprehensive guide to function rewriting in C

In C, function overriding allows derived classes to override functions in base classes. This is useful when extending base class functionality or modifying its behavior.

Syntax

To override a base class function, the function in the derived class must:

  • Have the same name as the base class function
  • Have the same signature (parameter list and return value)
  • Use the override keyword

For example, consider the following base class:

class Base {
public:
    virtual void print() { std::cout << "Base class" << std::endl; }
};

To override the print() function, derived classes can use the following syntax:

class Derived : public Base {
public:
    override void print() { std::cout << "Derived class" << std::endl; }
};

Practical case

Consider a Shape base class and a Circle derived class:

class Shape {
public:
    virtual double area() { return 0; }
};

class Circle : public Shape {
public:
    double radius;

    override double area() {
        return 3.14 * radius * radius;
    }
};

In the main() function, we can use virtual method scheduling to call these two methods :

int main() {
    // 创建一个圆形对象
    Circle circle;
    circle.radius = 5;

    // 通过基类指针调用派生类函数
    Shape* shape = &circle;
    double area = shape->area();

    std::cout << "Area of the circle: " << area << std::endl;

    return 0;
}

Output:

Area of the circle: 78.5

The above is the detailed content of How to override base class function in C++?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn