How to call the appropriate constructor
Regarding your use case, here's what each line calls:
Geometry geometry(0.3, 32, 0.0, 0.0, "SPHERE", true); // Geometry constructor 2
Container cont("Sphere", "SPHERE", geometry); // Container constructor 2, Geometry constructors 3 & 1
Here, the constructor for Geometry
is actually called outside the constructor of Container
. But Geometry constructor 3 and 1 are also being called... why?
Why indeed. Since the constructor for Container
takes a Geometry
parameter by value, the geometry
object passed will be copied (hence, the copy constructor is called). Next, Geometry constructor 1, aka the default constructor is actually called in the constructor of Container
. Afterwards, copy-assignment, another implicitly-generated special method, is called:
Container::Container(std::string strName, std::string strType, Geometry geometry)
/*: stdstrContainerName()
, stdstrPluginType()
, Geom()*/ // default-constructors implicitly called as member-initialisation
{
stdstrContainerName = stdstrContainerName;
stdstrPluginType = stdstrPluginType;
Geom = geometry; // copy-assignment, i.e. operator= (Geometry const&)
}
To override the default behaviour, use member initialisation explicitly:
Container::Container(std::string strName, std::string strType, Geometry geometry)
: stdstrContainerName(strName)
, stdstrPluginType(strType)
, Geom(geometry) // copy-constructor, i.e. Geometry(Geometry const&)
{
}
This should yield constructor 3, as the copy-constructor is now called.
Demo
On switching over to member initialisation, you may have noticed that constructor 3 is called twice. Again, this is due to the constructor of Container taking its geometry
parameter by value, creating a new object via copy-constructing. To prevent a copy from being made and make the constructor more efficient, we can pass geometry
by reference. In addition, we can const-ify the parameter to guarantee that the reference isn't modified in the constructor.
Thus the constructor of Container
can be changed to:
Container(const std::string &strName, const std::string &strType, const Geometry &geometry);