Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: C++ Design Beginner
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 23-Apr-10 12:46pm
Edited 24-Apr-10 0:20am
Moak11.4K
v3
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 4

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;
}
  Permalink  
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 3

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.
  Permalink  
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 2

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
  Permalink  
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

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.
  Permalink  
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 5

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 Smile | :) .
  Permalink  

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

  Print Answers RSS
0 OriginalGriff 5,130
1 DamithSL 4,237
2 Maciej Los 3,700
3 Kornfeld Eliyahu Peter 3,470
4 Sergey Alexandrovich Kryukov 2,846


Advertise | Privacy | Mobile
Web04 | 2.8.141216.1 | Last Updated 24 Apr 2010
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100