Ned help regarding passing object referance

I have a class whose member is another class' object like below

class test
{
A aobj;
void testfunc()
{
aObj.bObj.printval(&aObj);
}
};
class A
{
public:
int m_id;
B bObj;
}

class B
{
public:
void printval(A *aobj);
}

i need to use class A's members inside printVal function. So i am passing referance of object A to printval like below in testfunc() of class test

aObj.bObj.printval(&aObj);

Is there any other better way to do this? new to c++ so please guide me here
you are passing a pointer.
printval expects a pointer, so you have to take its address, and pass it a pointer, which you did.

& is used as 'reference' and also as 'take the addresss of'.

to keep the & operator straight, think of it this way : when you define it and give it a name, the & is reference. Eg int &x = y; is a reference to y, or void foo(int &x) makes x a reference (creation of variable x as a parameter here, this is where it is given the name x). If you already had it: int x; ... z = &x; That is 'address of' not 'reference' and implies that z is a pointer variable. Its extra critical to understand the slight difference here because pointers and references are extremely similar in many ways. There are a couple of operators that mean different things depending on context and this is one of them, and arguably the most confusing one at first.

you could not ask for a pointer: remove the * and put &
then call it with aObj.
void printval(A &aobj)
... printval(aObj);

this is going to have the same major effect (aobj is still passed around efficiently in both approaches) but you don't need the & on every use.

once you understand this, go ahead and learn about when to use constant references (passing into a function by reference, but keep it constant so the function cannot modify the input) and begin to get in the habit of using those to protect your data while still passing it efficiently.
Last edited on
Thanks for the detailed explanation


similar cyclic dependency asked on http://www.cplusplus.com/forum/general/268910/


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class A;

class B
{
 public:
 void printval(A *aobj);
}


class A
{
 public:
 int m_id;
 B bObj;
}



class test
{
 A aobj;
 void testfunc(){
 aObj.bObj.printval(&aObj);
}
};



Last edited on
Topic archived. No new replies allowed.