Here's the code
class C {
public:
void baz() {std::cout<<"~";}
};
class B {
public:
B() {c = new C();}
~B() {delete c;}
void bar() {c->baz();}
private:
C* c;
};
class A {
public:
A(): b(B()) {};
A(B arg_b): b(arg_b) {};
void foo() {b.bar();};
private:
B b;
};
int main() {
A a;
a.foo();
A aa{B()}; // will give the exit code 134 error
aa.foo();
}
As shown in the code, Class A has two constructors, calling the second constructor as above will give the following message
Process finished with exit code 134 (interrupted by signal 6: SIGABRT)
, while the first works fine.
Could someone please explain what is the difference between this two methods? what is the correct way of passing an instance as the initial value of a class member?
EDIT
As has πάνταῥεῖ has commented, delete
is applied twice for the same pointer c
. Adding the copy constructor B(const B& arg_b) : c(new C(*arg_b.c)) {}
to B solves the problem, assuming the copy-constructor of C is valid.