You are here:

C++/accesssing the private member of a class


Hello Bill,

i learnt that when u inherit a class, you can't access the private member of that class but someone told me there is a way to do this. let me give example:

class counter{
   private :
       int count;
   public :
   getcount(){return count;}

//inherited class

class count :public counter{
  private :
   int age;
 public :
   int getage(){};

I actually do not have a good example but i know u understand what i mean. those are two classes a base and an inherited one. could u just use them to demonstrate how i could access the private member of the base class?  

Hi Henry - how are you?

No you cannot acces a private member.  private is for objects of that class only.  If you want to access them in derived classes, you should use protected.  protected is for this purpose.  Only member functions in the base and derived class can access protected members.  Of course public is any function can access and objects public members.

There is no way to do this with private.  Someone who told you may have been meaning to use protected instead of private.  Is this right?  What the person may also have mean is what you did in counter.  A private count member with a public getcount member function that returns the private data.  I myself tend to do this, making the public get functions inline to make them as efficient as accessing the private data.  It's more a matter of style - something has to be public to get at the data.

Hope this helps.



All Answers

Answers by Expert:

Ask Experts


Bill A


I can answer questions about C++, programming algorithms, Windows programming in MFC (which is C++). I cannot answer questions about STL (templates) and I have no experience with Linux. I do enjoy reviewing code and critiquing it or finding problems in it. I will also gladly show better algorithms or methods if you want to take advantage of that.


I've developed a commercial embedded C compiler/assembler and IDE with debugger toolset, of which the IDE and debugger are written in C++. I work in the industry writing high tech embedded programs and Windows programs to communicate with the embedded devices.

Book: Embedded Systems Design using the Rabbit 3000 Microprocessor Authored Chapter 10 in its entirety.

BS Computer Engineering

©2017 All rights reserved.

[an error occurred while processing this directive]