Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Accessing data member in a specific class hierarchy????

Status
Not open for further replies.

annie1975

Programmer
Jul 22, 2003
4
IN
Hi
There is a situation like the following.
class A
{
public:
int x;
};
class B: -------- A
{
// I should not access the x in this class
};
class C: -------- B
{
// I should access the x in this class
};

How is it possible, if yes.

debasis
 
class B: -------- A
Does this mean that B descends from A ?

If so,

If you made x Private, and in Class A had a GetX() and SetX() function, then you could override these in B to return nothing, or a Null value, ie

Class A
{
const int GetX(){return X;}
int SetX(int mynum){X = mynum;}
}

Class B
{
const int GetX(){return 0;}//As long as X is never 0, you will be ok here
int SetX(int mynum){;}
}

this isn't very elegant, but it should work

If there is no definite need for the classes to descend from each other, you could use friend functions.

But if you need to descend B from A, and C from A, and not give B Access to some of A, then I would rethink the design slightly, (can you make B the Base class, and then Inherit B ->A, and A-> C ?
but not knowing what you are trying to do thats a little hard. (you may get a better answer in the Object Oriented Forum)
 
with x being public, you can derive B though protected inheritence, and then provide public accessessors and mutators in C, through public inheritence.

Code:
class A
{
public:
 int x;
};

class B : protected A
{
//has x, but isn't acessisible to the outside world 
//(it is now a protected member.)
};

class C: public B
{
public:
  const int getX(){return x;}
  void setX(int a){x=a;}
};
cheap, dirty, short, crude but there you go....
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top