Search code examples
c++inheritancemember-functionsdatamember

Inherited member function accessing data members


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


Solution

  • 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.