Why use pointers at all when you can return a link?
Foo& B::getFoo() { vec.push_back(Foo()); return vec.back(); }
Note that references, pointers, and iterators to vector content become invalid if redistribution occurs.
Also, having public member data (e.g. your vec here) is not good practice - it is best to provide access methods for your class as needed.
source share