I have spent a couple hours looking for discusion on this both in some good C++ books as well as here on stack overflow, and while I have seen quite a number of questions regarding the “heap vs stack” question, I’m looking more specifically for an understanding of the use of pointers or not in creating object members of a class, i.e. with composition.
For example:
class A{
B c;
}
vs.
class A{
B*c;
}
In the first example, this is not really a “stack” allocation, rather an allocation in the “static storage area,” which is a different thing, so discussions of stack vs heap don’t apply, I think.
What’s not clear to me are the pros and cons of either. It seems like most code I read is using the second option, but why?
It’s possible I don’t know the proper terminology of these techniques to search this site properly, or else there simply haven’t been questions on this. If there are indeed answers pertaining to this elsewhere, by all means let me know how to find them, but nearly everything seems to be more about stack vs heap in the context of a local variable, and I think I have a handle on that okay.
The reason why people use the 2nd option is this:
This simple feature of C++ makes it difficult to build working system with the B b; style. You have to put all related classes to same file and reorder the classes to exactly correct order.
Also inheritance does some magic with the order too:
So using inheritance and B b; together is fixing the order of classes completely and large number of data members will be nightmare. (note that types like float and int does not have the order problem – and it’s possible to do it correctly for classes too)