I am often seeing these kinds of declarations:
class A
{
private:
int a;
int b;
public:
// Ctor + Dtor + methods
};
class B
{
private:
int a;
int b;
public:
// Ctor + Dtor + methods
};
class C
{
private:
A* aClass;
B* bClass;
// Other members.
public:
// Ctor + Dtor + methods
};
aClass
and bClass
are dynamically allocated with the new operator.
Assumption
A lot of people tend to use the heap when there is apparently no reason to. Dynamically allocating A
and B
classes will decrease the size of the C
object on the stack. However, the new operator is "costly" (execution time), and suppose we have getters and setters for all the variables contained in A
and B
, setting or getting a member of A
and/or B
will lead to some extra computation in order to access A
or B
(dereference A
or B
and then proceed to an operation).
Here are my questions:
Would it be better to write the following?
class C { private: A aClass; B bClass; // .... }
Can proceeding this way with large objects lead to a stack overflow?
Is the compiler able to proceed to some optimization if he does not know the "true type" of
A*
andB*
?
Edit
I forgot to mention that C is a composition, in both cases (thanks C.LECLERC). The first case is used to realize a composition.