Is it possible to initialize objects of one class in the constructor of another class in c++? I usually will declare objects only in the main(), however I am curious to know if this is possible and a good practice. What are the implications with “new” and a case without “new” operator. Where does it get destroyed?
e.g. Assuming one namespace and an example with “new” operator
class A{
private:
protected:
int *w, int *h;
public:
A(){
w = new int;
h = new int;
};
virtual int area (return ((*w)*(*h)) ;)
virtual ~A()
{
delete w;
delete h;
}
}
class B{
public:
B()
{
A a1; // This is usually in the main();
// Is this good practice
//Where will the object be destroyed
}
virtual ~B();
}
About your actual question, yes this is perfectly good practice (as far as declaring A inside B’s constructor goes). This will work and properly call A’s destructor.
However: About the code snippet you posted, allocating two objects in A’s constructor is not good practice. If
operator newforhfails, thenwwill be leaked. A’s destructor will not be called if an exception is thrown inside its constructor. Thus,wwill not be deleted ifnew intthrows forh.