How to get a derived class to access private member data?

I am stuck in a C ++ issue. I have a base class that has a pointer to a self-referencing object inside the private scope of the class. I have a constructor in a base class that initializes these two pointers. Now I have my own derived class whose access specifier is private (I want the public member functions of my base class to be private). Now, through the member functions of my derived class, I want to create an object pointer that can point to the private data of the base class, that is, to these self-relational 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. } 
+6
source share
3 answers

A derived class cannot access private members of its base class. No type of inheritance allows access to private members.

However, if you use the friend declaration, you can do it.

+11
source

There is no other way to access other private class data, and then friendship. However, you can make access to the protected data of the base class with inheritance. But this does not mean that you can access the protected data of another object of the base type. You can only access the protected data of the base part of the derived class:

 class base{ protected: //protected instead of 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(3); //temp->ptr1 = 0; //you need friendship to access ptr1 in temp this->ptr1 = 0; // but you can access base::ptr1 while it is protected } int main(){} 
+4
source

try to provide a secure access specifier in the base class and inherit the base class in private mode ..... but for further use of member functions of the base class u you may need several short built-in functions, as they will also be converted to a private

+2
source

Source: https://habr.com/ru/post/954348/


All Articles