Link to home
Start Free TrialLog in
Avatar of sagitarian
sagitarian

asked on

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 ?
ASKER CERTIFIED SOLUTION
Avatar of rigansen
rigansen

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of rigansen
rigansen

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.
Protected is the way to go.  That is what protected is for.
Avatar of sagitarian

ASKER

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.
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 ??

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.