My questions is, suppose we have two classes A and B. I want to have an object of B in class A.
Should I use,
class A
{
public:
A();
~A();
B* b;
};
or
class A
{
public:
A();
~A();
B b;
};
As far as I know, in the first scenario, I can initialize the object *b
using new
operator and for the second scenario, I can initialize b
using an initialization list if I don't want to use the default constructor of class B
. Which is more convenient to use?
It depends.
Even if you use the pointer, you can initialize the member in the initialization list, but that's not your biggest concern.
There are advantages and disadvantages to both:
the class will be smaller in memory
you only need a forward declaration to the other class - no need to include the other header in your header
can use derived objects from B
as members
can only use objects of the base class. What if you want to derive from B
?
more memory for each instance
constructor of B
will be called on construction of A
you need the full definition of B
inside the header
I'll edit my answer if I think of more.