Click here to Skip to main content
15,884,628 members
Please Sign up or sign in to vote.
3.00/5 (1 vote)
See more:
Class B is instantiated in class A:

Class A {
int x, y;

B b;
}


How can I use variables x and y from member functions of class B?
Posted
Updated 23-Apr-10 23:20pm
v3

I think, it better if you get some more knowledge regarding class design.
So i prefer you to have a look with some book in C++ like C++ Primer from Stanley B Lippman.

Well see your case

class B
{
public:
  void SetAVal( int X1, int Y1 )
  {
     LocalX = X1;
     LocalY = Y1;
  }
private:
   int LocalX, LocalY;
};

Class A {
int x, y;
void SetValTOB()
{
  b.SetAVal( x, y );
}

B b;
}
 
Share this answer
 
You should buy a book on C++ and read the chapters on how object oriented programming works. Your question makes no sense. Class A has no variables, instances of class A do. If B has an instance of A, it can access the variables in A. A has an instance of B here, and can access values in it, if they are public. You'd have to pass the instance of A into the function in B, or pass the x/y values in directly. It can't access them otherwise.
 
Share this answer
 
You cannot directly use variables declared in A in any other class, whether nested or not. You will have to pass an instance of A and then use member functions of A to access its variables.

-Saurabh
 
Share this answer
 
Since B knows nothing about the classes into which it may be instantiated, it has no way of knowing whether such classes will always, never, or sometimes, have fields named 'x' and 'y'.

What you need to do, I think, is have the object of class A tell class B about itself when instantiating B (e.g. by having B take a parameter of type A in its constructor). Class B would then be able to use any public methods or properties of the item of class A that was passed in.
 
Share this answer
 
I think your question is very basic and if you will read a little more about classes in c++ then you will get the answer yourself. Just read a bit more, don't jump to the exercises at the end of chapter or to your project :) .
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900