 |
C++Talk.NET C++ language newsgroups
|
| View previous topic :: View next topic |
| Author |
Message |
Guest
|
Posted: Mon May 14, 2007 8:17 am Post subject: class cross-reference |
|
|
How does the compiler solve class cross-reference? Is it valid at all?
In the example below class A stores a reference to class B that stores
a reference to class A. Both references are set in the constructor.
The instantiation of the two class takes place in the constructor of
class C.
This piece of code worked for me in different compilers; however I
cannot understand how it is done.
Please make your comments!
Thanks!
class A {
public:
A(B& b) : mB(b) {}
private:
B& mB;
};
class B {
public:
B(A& a) : mA(a) {}
private:
A& mA;
};
class C {
public:
C() : mA(mB), mB(mA) {}
private:
A mA;
B mB;
};
int main() {
C myC;
return 0;
}
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ] |
|
| Back to top |
|
 |
Sebastian Redl Guest
|
Posted: Mon May 14, 2007 4:37 pm Post subject: Re: class cross-reference |
|
|
On Mon, 14 May 2007 gergomeister (AT) gmail (DOT) com wrote:
| Quote: | This piece of code worked for me in different compilers; however I
cannot understand how it is done.
|
And none gave you any warnings at all? Typically they warn about this.
It's not that it is undefined behaviour. Wehn A's constructor is called,
mB is uninitialized, but as long as A's constructor doesn't convert it to
an R-value or access any members of it, the behaviour is defined.
It's just that it's a potentially dangerous thing to do.
As for how it works, well, that's an implementation detail. Typical
implementations implement references as pointers, so A's constructor
simply receives the memory address where mB will be constructed later.
Sebastian Redl
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ] |
|
| Back to top |
|
 |
|
|
You cannot post new topics in this forum You cannot reply to topics in this forum You cannot edit your posts in this forum You cannot delete your posts in this forum You cannot vote in polls in this forum
|
|