简体   繁体   中英

accessing all the private members of a class c++

I have created few class as below (Since I can not put my real class Here I have written few as just example )

 class One {
      private :
         char *link;
         int count 

        }


 class Two {
      private :
         char *link;
         int count 

        }

 class  Three :: public TWO  {
      private :
         char *link;
         int count ;
          One One_object;

        }

 int main() {

     Three test;
     cout << test.One_object.link ; // error becoz of accessing private member 

       }

Here what would be the best way access the private mebers , if it is only value to acess then I could have written a get method function to get the data .

But in my real class has many data members are protected .. Can you somebody through light on this ..

The private and protected member variables are meant to be accessed using member functions aka methods .

The methods which are meant to be used only internally from another method of the same class but not from outside should again be private or protected.

Choosing private vs protected depends on if you'll be inheriting from that class or not. It is recommended to use protected for all the members so that any class which inherits (may be in the future) from this class also benefits by getting access to these members.

And there are friend functions which let you access private or protected members from outside directly too.

In main , when you do test.One_object (you need to mark One_object as public though), you are getting the One object instance directly, but even then you can not access the private members of One because they are not visible from this context. So, you have two options:

1) If Class One is editable, you need to mark the variables you MUST access from main as public

OR

2) Make Three a friend class of One and write a getter function for each member variable of One_object in Three .

So, following option 2-

class One {
      private :
         char *link;
         int count;

      friend class Three;
};
class  Three : public Two  {
      private :
         char *link;
         int count ;
      public:
         One One_object;
         int get_One_object_count(){
            return One_object.count;
         }

};

I think you may reconsider the design of your classes as accessing the members from global context is not a very good design practice.

Read more about friend class and friend functions here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM