C++ same-name hiding and assignment compatibility rules

Encapsulation, inheritance, and polymorphism are the three major characteristics of object-oriented. For each feature, there are many detailed knowledge points. Here, we mainly introduce the same-name hiding and assignment compatibility rules in inheritance.

Same name hiding: As long as the function name in the subclass is the same as the function name of the parent class, the function in the subclass will hide all functions with the same name in the parent class and the subclass, as long as the name is the same, regardless of the parameter list. Note the difference with function overloading.

#include<iostream>
#include<stdio.h>
#include<string>

using namespace std;

class A
{
public:
    A() {}
    ~A() {}
    void setStr(string str)
    {
        cout<<"class A"<<endl;
    }
};

class B : public A
{
public:
    B() {}
    ~B() {}
    void setStr(char ch)
    {
        cout<<"class B:"<<"char"<<endl;
    }
    void setStr(double d)
    {
        cout<<"class B:"<<"double"<<endl;
    }
};

int main()
{
    B b;
    b.setStr('A'); // 1
    b.setStr(12.120); //2
    b.setStr("helloWorld"); //3

    b.A::setStr("helloWorld"); //4

    return 0;
}

In the above code, lines numbered 1 and 2 will behave correctly according to the rules of function overloading. Label 3 is wrong. Because the function in the parent class A is hidden, there is no corresponding function in the child class B that can handle the string type.
If you want to use the function in the parent class A, you can follow the way labeled 4.

Assignment Compatibility Rules:
Concept: Anywhere a base class object is required, a public derived class object can be used instead.
In the shared inheritance mode, the assignment compatibility rules stipulate:
(1) The derived class object can be assigned to the base class object. At this time, in the derived class object, the hidden part inherited from the corresponding base class is assigned to the base class object
(2) ) The address value of the derived class object can be assigned to the object pointer of the base class, but only the hidden object inherited from the base class in the derived class can be accessed through this pointer, and new members in the derived class cannot be accessed
(3) The derived class object can Used to initialize the base class object reference, but this reference can only contain hidden objects inherited from the base class in the derived class object

Using the above rules, two points must be noted:
(1) must be public inheritance
(2) the above conditions are irreversible

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324029857&siteId=291194637