I have the following classes:
class A { public: A() { x = 0; std::cout<<"A default ctor()\n"; } A(int x_) { x = x_; std::cout<<"A normal ctor()\n"; } int x; }; class B { public: B() { std::cout<<"B ctor()\n"; } private: std::string str; };
and a function that creates object B, taking object A as a parameter:
B createB(const A& a) { std::cout<<"a int: "<<ax<<"\n"; return B(); }
if I create a class C that has elements of type A and B, and constructs a B-object before the A-object is built , but using the A object for this , it will compile without warning, but it will silently introduce an error:
class C { public: C(): b(createB(a)), a(10) {} private: B b; A a; }; int main() { C c; return 0; }
Of course, the above example is trivial, but I saw it in the real world, in a much more complex code (this is Friday, 8:30 pm, and I just fixed this error, which led to segfaults).
How can I prevent this?
source share