a cpp question

Started by
3 comments, last by ToohrVyk 17 years ago
Hey, I just how to solve this:

class CClassOne
{
private:
CClassTwo classtwo;
int a;
};

class CClassTwo
{
public:
int add_a();//I just want to increase a of CClassOne, how can I do?
};
Thanks!
Advertisement
CClassOne is a class. CClassOne::a is not a static variable. Therefore: of which instance of CClassOne do you want to increase the member variable a ?
Quote:Original post by ToohrVyk
CClassOne is a class. CClassOne::a is not a static variable. Therefore: of which instance of CClassOne do you want to increase the member variable a ?

Sorry, may be I didn't make myself clear enough. I just want to know, if an instance of CClassOne is already exits, say classone. How can classone's data member classone.classtwo's function member add_a() access the data member a in classone.
I'm guess he wants it to increase the 'a' member of the same CClassOne parent that the CClassTwo object is a member of...

However, the CClassTwo object does not have that information, as it stands. That means that e.g. if it is a standalone CClassTwo instance, the above comment wouldn't make sense.

jhq: you need the CClassTwo to point to the parent. Something like this.

class CClassOne{private: CClassTwo classtwo(this); // can't quite remember if this is legit. or not                           // maybe use a SetParent() function if not. int a;};class CClassTwo{public: int add_a();//I just want to increase a of CClassOne, how can I do? CClassOne * parent; CClassTwo(CClassOne * p) { parent = p; } // constructor};int CClassTwo::add_a(){ parent->a++; return parent->a;}
Positronic Arts [blog]
Incorrect encapsulation. CClassTwo here assumes each of its instances will be owned by a CClassOne instance. This is incorrect, because it is always possible to instantiate CClassTwo on its own, as follows:

CClassTwo myInstance;myInstance.add_a(); // What does this call do?


Since your instance intends to alter an instance of CClassOne, let that instance be provided. acemuzzy above outlined the basic idea behind this. The actual implementation:

class CClassOne;class CClassTwo{  CClassOne & parent;public:  CClassTwo(CClassOne & parent) : parent(parent) {}  void add_a()   {    ++parent.a;  }};class CClassOne{  friend class CClassTwo;  int a;  CClassTwo classtwo;public:  CClassOne() : classtwo(*this) {}};

This topic is closed to new replies.

Advertisement