I have been using Java for a very long time and I have problem getting used to C++ programming styles.
How we can manage scenarios like below:
-
Instance variables are objects which cannot be created using default constructor. In java constructor parameters can be decided upon in higher level class constructor.
-
Instance variable is a reference type and we need to run a simple algorithm (condition, calculation,…) in the constructor and then create and assign an object to that reference.
There are possibly similar scenarios in which we need to initiate instance variables in places other than the constructor initialization list. I guess GCC would allow to do that (issues a warning), but VC++ does not seem to allow.
I guess most of these can be done using pointers but I am trying to avoid pointers as much as I can (to minimize run-time crash and also hard to debug problems).
You can hide more complicated computations in (static) helper functions, of course, having
ref(f(parameters))in the initializer list.If you need to create an object first and then assign it to the reference, where does that object primarily live? A reference, after all, is just someone pointing at someone else saying “that’s me, over there.” If your outer object is actually the one owning this object, you don’t want a reference. You either want an object or a smart pointer.
A Java reference is probably closest to C++11’s
std::shared_ptr, one of the smart pointers of the standard library highly recommended for everyday use. In this kind of setting, you might also want to considerstd::uniqe_ptr, which has a little less overhead, but comes with limitations. Whether the fact that it requires you to create a proper copy constructor is a problem is a matter of taste – pretty often, the default constructor combined withshared_ptris not the behavior you want, anyway.Stay clear of
std::auto_ptr, which is only in the language for backwards compatibility – it’s tricky to use correctly in a lot of situations.