Sign in to follow this  
Cragon

[C++] Dilemma with Classes

Recommended Posts

I've tried searching Google and GameDev for the answer, but I don't really know the name for what I'm trying to do, so it was kinda hard. Obviously, I didn't find an answer otherwise I wouldn't be posting this question.
class ClassA {
   public:
      void Function();

   private:
      int k;
}

class ClassZ {
   public:
      ClassA har;

   private:
      int i;
}


void ClassA::Function() {
   k = i;
}
Ok. Let's say we have the classes above. Basically, ClassA is a class within ClassZ, and ClassA has a function which needs to do something based on an integer of ClassZ. How would I gain access to it? If I haven't explained it right, let me know. I'll try to clarify.

Share this post


Link to post
Share on other sites
You can't access i in ClassA::Function() because its private in ClassZ which ClassA doesn't know about...

I'm not sure what you're trying to do either. What is your aim?

Share this post


Link to post
Share on other sites
What you have there is composition, or a HAS_A relationship...class Z HAS_A class A.

Since A is a member of Z, but needs to use the integer, why not pass it as a parameter:

void Z::DoSomethingWithA ()
{
har.Function (i);
}

Share this post


Link to post
Share on other sites
Unfortunately your example is very abstract, but the best way to get Function in ClassA to manipulate i in ClassZ is, to pass it as a parameter.

Either add an int parameter to the method Function and then pass i or make i public accessible (using whatever method you prefer) and pass ClassZ as parameter to "Function".

I hope that helps!

Share this post


Link to post
Share on other sites

class ClassZ;
class ClassA {
public:
void Function();
ClassZ* parent;
ClassA(ClassZ* p):parent(p) {}

private:
int k;
}

class ClassZ {
friend class ClassA;
public:
// upgrade to smart ptrs later.
ClassA* har;
ClassZ() { har = new ClassA(this); }
~ClassZ() { delete har; }
private:
int i;
}


void ClassA::Function() {
k = parent->i;
}

int main()
{
ClassZ foo;
foo.har->Function();
return 0;
}



HTH.
- Pete

Share this post


Link to post
Share on other sites
Alright, thanks for the replies.

I'm new to Object Oriented design, so I'm just trying to see how to design my game and such. Apparently, this won't come to me overnight, but I never expected it to :D

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this