Home > Mobile >  Accessing private member of base class using derived class member function
Accessing private member of base class using derived class member function

Time:09-29

I have just started learning about inheritance and I know that private members of base class are not inherited by the derived class.

But when I run the 'get_data1' function of the derived class, it returns the value of data1 from the base class even though I have defined a new 'data1' in the derived class. So shouldn't it return 3 instead of 5 as it is a member function of the derived class?

class base
{
    int data1;
    public:
        base()
        {
            data1=5;
        }
        int get_data1()
        {
            return data1;
        }
};

class derived : public base
{
    int data1;
    public:
        derived()
        {
            data1=3;
        }
        void printData()
        {
            cout<<get_data1()<<endl;
        }
};
int main()
{
    derived der1;
    der1.printData();

    return 0;
}

CodePudding user response:

I know that private members of base class are not inherited by the derived class.

No, private members are inherited just like other members. The difference is that they're not accessible from the derived class unlike public or protected members.


shouldn't it return 3 instead of 5 as it is a member function of the derived class?

No, you're confusing calling printData with calling getdata1. Even though printData is a derived class member function, it calls the base class' base::get_data1 member function which prints the base class' data member and hence the output.

See the added comments in the below program.

class base
{
    int data1;
    public:
        base()
        {
            data1=5;
        }
        int get_data1()
        {
            return data1;  //this prints base class' data1's value
        }
};

class derived : public base
{
    int data1;
    public:
        derived()
        {
            data1=3;
        }
        void printData()
        {
            cout<<get_data1()<<endl; //this calls base class' base::get_data1()
        }
};

int main()
{
    derived der1;
    der1.printData(); //this calls derived class' derived::printData()

    return 0;
}

CodePudding user response:

Just create extra constructor in base:

class base {
    int data1;

public:
    base()
        : base(5)
    {
    }
    explicit base(int initial)
        : data1 { initial }
    {
    }
    int get_data1() const
    {
        return data1;
    }
};

class derived : public base {
public:
    derived()
        : base(3)
    {
    }
    void printData()
    {
        std::cout << get_data1() << std::endl;
    }
};

https://godbolt.org/z/aqxhTjTYa

  • Related