Public Group

[C++] Dilemma with Classes

This topic is 5094 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

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 on other sites
ClassZ.ClassA.function();
or sometimes ClassZ->ClassA->function.

EDIT: oops, I didn't read it right

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

1. 1
2. 2
Rutin
21
3. 3
JoeJ
18
4. 4
5. 5

• 14
• 39
• 23
• 13
• 13
• Forum Statistics

• Total Topics
631717
• Total Posts
3001878
×