質問

Consider the sample code below:

#include <iostream>

using namespace std;

class A
{
    private:
        static int a;
        int b;

    protected:

    public:

        A() : b(0) {}

        void modify()
        {
            a++;
            b++;
        }

        void display()
        {
            cout << a <<"\n";
            cout << b <<"\n";
        }

};

int A::a=0;

class B : public A {

    private:
        int b;

    public:
        B(): b(5)
        {
        }

};

int main()
{
    A ob1;
    B ob2;
    ob1.display();
    ob2.display();

    return 0;

}

In the code above, the class A has a private data member band class B also has a private data member b. The function display() is used to display the data members. When i invoke display() using ob1.display(), display() accesses the private data member b of class A. I understand that. But when i invoke display using ob2.display, which b does display() access? Is it the b of class A or b of class B? Kindly explain the why it accesses class A's b or class B's b

役に立ちましたか?

解決

It will access A::b. The display method implementation in class A has no clue about the existence of B::b at all, let alone using it. For all intents and purposes, B::b is separate from A::b. Only in the scope of B itself, the name conflict makes b refer to B::b, hiding A::b. Member variables cannot be virtual.

他のヒント

ob2.display() will access the derived class member.
The member function call is always evaluated on this, this->display() the this in case points to object of your Base class and hence any reference to b inside the display() function is evaluated as this->b which is b of the Base class.

This is because display() of the Base class has no knowledge of whether any other class derives from it. Base class is always independent of the Derived class. To solve a problem the uual pattern followed is to provide a display() method in the Derived class which then in turn calls the dsiplay() method of the Base class.

void B::display()
{
    //cout << a <<"\n";
    cout << b <<"\n";
    A::display();    
}

It is class A. A::display() cannot access B private members.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top