why in C++, for objects A,B
//interface, case #1 class A { B bb; } A::A() { //constructor bb = B(); } //interface, case #2 class A { B *bb; } A::A() { //constructor bb = new B(); }
Why case #2 work but not #1??
Edit: I got it now. But for case #1, if an instance of A is freed, will its bb also be automatically freed? Case #2 you have to explicitly call bb = NULL right?
The question as for me was how to make
but without new. And I suppose the code in the question is not a real code. Just why ‘new’ works but simple assignment doesn’t.
And my answer is following. If I understood the question in a wrong way or the answer itself is wrong – please let me know.
Change
to
and to have a consistence in the case with ‘new’ it is better to implement like
In these both cases when ‘some logic’ will start its execution you can be sure that object bb either initialized or exception will be thrown.
To make your case compilable B should has implemented assign operator.
To your edit: Your guess about case 1 is correct. in case 2 you have to call delete bb in the class destructor.
Please leave a message of the ‘-1’ reason. I am really confused.