Home > Article > Backend Development > Detailed explanation of C++ function inheritance: What are upcasting and downcasting?
In inheritance, upward transformation converts the derived class into the base class, and downward transformation converts the base class into the derived class. Upcasting is safe, information may be lost; downcasting is dangerous, you must ensure that the corresponding derived class exists, otherwise nullptr will be returned.
C Upcasting and Downcasting in Function Inheritance
In object-oriented programming, inheritance is a class hierarchy Key concepts. When a class inherits another class (base class), the inheriting class (derived class) inherits the properties and methods of the base class.
Upcasting
Upcasting refers to converting a derived class object into a reference or pointer to a base class object. This type conversion is safe because the derived class object contains all the data and methods of the base class object, but it may result in a loss of information because the unique methods and data of the derived class will not be accessible after the conversion.
Syntax:
基类* 指针 = &派生类对象;
Downcasting
Downcasting refers to converting a base class object into a derived class object reference or pointer. This type conversion is dangerous because it can lead to invalid casts. Downcasting only works if the derived class object actually exists in the base class object.
Syntax:
派生类* 指针 = dynamic_cast<派生类*>(基类对象);
dynamic_cast
The operator will perform runtime type checking to ensure that the cast is safe. If the cast is invalid, dynamic_cast
will return nullptr
.
Practical case
Suppose we have a Shape
class as the base class, which has a getArea()
method to Calculate the area of a shape. The derived class Square
inherits the Shape
class and adds a getWidth()
method to get the width of the square.
Shape.h
class Shape { public: virtual double getArea() const = 0; };
Square.h
class Square : public Shape { public: explicit Square(double width); double getArea() const override; double getWidth() const; private: double width; };
main.cpp
#include "Shape.h" #include "Square.h" int main() { // 创建一个正方形对象 Square square(5.0); // 将正方形对象向上转型为形状对象 Shape* shape = □ // 通过形状对象调用 getArea() 方法 double area = shape->getArea(); std::cout << "正方形的面积: " << area << std::endl; // 将形状对象向下转型为正方形对象 Square* square2 = dynamic_cast<Square*>(shape); // 如果向下转型成功,则调用 getWidth() 方法 if (square2) { double width = square2->getWidth(); std::cout << "正方形的宽度: " << width << std::endl; } else { std::cout << "向下转型失败" << std::endl; } return 0; }
In this example, we create a square object, upcast it to a shape object, and call the getArea()
method. Then, we downcast the shape object to a square object and call the getWidth()
method.
The above is the detailed content of Detailed explanation of C++ function inheritance: What are upcasting and downcasting?. For more information, please follow other related articles on the PHP Chinese website!