Answer the question
In order to leave comments, you need to log in
Why does the compiler reinitialize an object?
Why is copy ctor called after object initialization?
//-std=gnu++03 -fno-elide-constructors
//-std=gnu++11 -fno-elide-constructors
#include <iostream>
class A {
int data;
public:
A (void) { std::cout << this << " A::A (void) \n"; }
A (A const & ref ) { std::cout << this << " A::A (A const &) \n"; }
~A(){ std::cout << this << " ~A::A () \n";}
class B;
friend B;
class B {
A & a;
public:
B(A & objc) : a(objc) { std::cout << this << " A::B::B (A &) \n"; }
B(B const & ref) : a(ref.a) { std::cout << this << " A::B::B (B const &) \n"; }
~B(){ std::cout << this << " ~A::B::B () \n";}
};
int main(void) {
A a;
// A::B b1 (a); // ok
A::B b2 = a; // strange
std::cout << " end " << std::endl;
return 0;
}
Answer the question
In order to leave comments, you need to log in
Because of assignment. To assign an object of type B to an object of type A, you need to create an intermediate object of type B with the constructor (A::B::B (A &)). And only then assign (A::B::B (B const &)). And delete the temporary object. That's what the compiler thinks
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question