Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a derived class access the private member data?

Tags:

c++

I'm stuck with a c++ problem. I have a base class that has a self referential object pointer inside the private visibility region of the class. I have a constructor in the base class that initializes these two pointers. Now I have my derived class whose access specifier is private(I want to make the public member functions of my base class private). Now through the member functions of my derived class I want to create an object pointer which can point to the private data of the base class, that is ,those self referential object pointers. My code is:

class base{
private:
     base *ptr1;
     int data;
public:
     base(){}
     base(int d) { data=d }
};

class derived:private base{
public:
     void member()
};

void derived::member()
{
base *temp=new base(val); //val is some integer
temp->ptr1=NULL; //I can't make this happen. To do this I had to declare all the
                 //private members of the base class public. 
}
like image 975
Rahul Chitta Avatar asked Sep 22 '13 13:09

Rahul Chitta


People also ask

How can derived classes access private members?

Private members of the base class cannot be used by the derived class unless friend declarations within the base class explicitly grant access to them. In the following example, class D is derived publicly from class B . Class B is declared a public base class by this declaration.

How can a derived class access a base class private data field?

A base class's private members are never accessible directly from a derived class, but can be accessed through calls to the public and protected members of the base class.

Can private variables be accessed by derived class?

Private variables are specific to the Base class(Parent class) and can never be inherited in the derived classes(child classes).


1 Answers

Derived class can not access the private members of it's base class. No type of inheritance allows access to private members.

However if you use friend declaration you can do that.

like image 67
Rahul Tripathi Avatar answered Oct 09 '22 01:10

Rahul Tripathi