• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 181
  • Last Modified:

Access to private members by descendant classes

Suppose you have a certain class which has an attribute you want to maintain as private :

class A {

   private:

   int Example_Int;

   public:

   ...
};

Then you have a class which derives from the previous one, which has a certain member function.

class B : A {

   public:

   int Example_Function();
};

The member function just defined wants to have access to Example_Int without having to define it again on the derived class and without having to put it as public.

int B::Example_Function() {

   return Example_Int;           //Error
};


How to do it ?
0
sagitarian
Asked:
sagitarian
  • 3
  • 2
1 Solution
 
rigansenCommented:
Have you tried this:

class B : public A {
public:
   int Example_Function();
};

not completly sure, but maybe... if not leave a comment.


0
 
rigansenCommented:
seems that the fist try didn't work...

After some testing I think you have only two possibilities:

(1)

class A {
friend class B;
private:
   int Example_Int;
};



(2)

class A {
protected:
   int Example_Int;
};



the choice is up to you...

regards.

    rigansen.
0
 
nietodCommented:
Protected is the way to go.  That is what protected is for.
0
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
sagitarianAuthor Commented:
Even using the public specifier for class A access on class B, it still depends wether class A's attribute you use is public or not. Nevertheless, one should use class A as public or else none of the class member could be seen.

The protected solution is the best one. This way it works, which is the main purpose, but also is more understandable.

Thanks for the answers.
0
 
rigansenCommented:
Could someone explain ??

My answer was graded with a *D*  :(

Maybe I didn't hit the first time, but
wasn't it me who suggested in "Comment from rigansen..." the use of the 'protected' keyword ??

0
 
sagitarianAuthor Commented:
I graded the answer with a "B" because that was my evaluation of the "answer". Only then I saw the comment. I think that the comment should have been the answer in the first place.
0

Featured Post

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

  • 3
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now