In C++, whose responsibility is it to delete members of a class: the class, or the creator of an instance of that class?
For example, in the following code:
class B {
public:
B(int x) { num = x; }
int num;
};
class A {
public:
A(B* o) { obj = o; }
B* obj;
};
int main(void) {
A myA(new B(3));
return 0;
}
Should main delete the instance of B, or should A‘s destructor delete its local variable obj? Is this true in most cases, and in which cases if any is it not?
This is a basic question of ownership. If every
Ashould own aB(as in, there should be a newBcreated when theAis created, that should also be destroyed be theAis destroyed, then you’d normally makeAresponsible for creating and destroying the instance of B:In such a case, however, chances are pretty good that
Ashould just be written like:This way, the instance of
Bwill be created and destroyed automatically, without any intervention on your part at all.