Lelouch Yagami
Lelouch Yagami

Reputation: 159

Inheriting access to private data members of Base class (with Base class member function inherited in Derived class)

I have read that "A derived class doesn't inherit access to private data members. However, it does inherit a full parent object, which contains any private members which that class declares."

But, in the following program, I could access the private data member.What am I doing wrong?

#include <iostream>
using namespace std;

class A
{
    private:
    int x;
    public:
    void printdata()
    {
       cout<<"x="<<x<<endl; 
    }
};

class B:public A
{
};

int main() 
{
    B obj;
    obj.B::printdata();

    return 0;
}

Link to Program

Upvotes: 1

Views: 2551

Answers (2)

Archit J
Archit J

Reputation: 150

You are not doing anything wrong.

By definition of public inheritance, a base class's private members cannot be directly accessed from the derived class but can be accessed through calls to the public and protected members of the base class.

Refer to the C++ inheritance: https://www.tutorialspoint.com/cplusplus/cpp_inheritance.htm

Upvotes: 1

iOS_Maccus
iOS_Maccus

Reputation: 397

You are accessing the private member using the public member functions.

Thats the reason you are able to access the parent class private data member.

x is private data member and its not available for child class instance. Check below code for more detail

int main() 
{
    B obj;
    obj.x = 10; //Gives compilation error: 'int A::x' is private
    obj.B::printdata();

    return 0;
}

Upvotes: 1

Related Questions