简体   繁体   中英

Why can I print out a privately inherited member of the Base class through a publicly inhterited method of the SubBase class?

Student inherits privately from Person class. That means that protected and public members and methods are gonna be treated as private members and functions .

#include <iostream>
#include <string>

#define COUT std::cout
#define ENDL std::endl

class Person
{
protected:
    std::string name;

public:
    void set_name(std::string _name)
    {
        name = _name;
    }
};

class Student : private Person
{
public:
    void display()
    {
        COUT << "Name: " << name << ENDL;
    }

    void set_Student_name(std::string _name)
    {
        set_name(_name);
    }
};

class GStudent : public Student
{
public:
    void set_GStudent_name(std::string _name)
    {
        set_Student_name(_name);
    }
};

int main(void)
{
    GStudent martin;

    martin.set_GStudent_name("Martin");

Then, why does the line of code of below work? I had thought that it would just have threw an error because the GStudent publicly inherited method called display() is printing out a privately inherited method that doesn't belong to the GStudent class but it belongs to Student class.

    martin.display();

    return 0;
}

You never have to care about the body of a method to know if you can call it.

You can call display because it is a public member of a public base of martin . That line would still be legal if Person::name were made private. In that case, the error would be in the body of Student::display .

It would be nonsensical otherwise. Imagine if you were restricted to only accessing things with the same access control. You wouldn't be able to construct private members, the constructor is invoked from outside the class. You wouldn't be able to read private members, because eventually you are called by something outside the class. Everything would have to be public to be usable, so there would be no access control.

std::string nameStudent类中是私有的(因此可以访问),因为它在Person类中受保护。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM