Passing a class member to the constructor of the base class (by reference)

Given the following classes, where ConcreteBar implements BarIfc :

 class Base { public: Base(BarIfc& bar) : _bar(bar) { } void foo() { _bar.bar(); } private: Base(const Base& other); Base& operator=(const Base& other); BarIfc& _bar; // Pure virtual interface }; class Child : public Base { public: // bar is passed to base class before initialization Child(int i) : Base(_bar), _bar(i) { } private: Child(const Child& other); Child& operator=(const Child& other); ConcreteBar _bar; }; 

Do I believe that this

 Child(int i) : Base(_bar), _bar(i) {} 

is "valid" C ++ if I do not use (for example, a method call) the _bar link in the list of initializers of the base class?

+7
c ++
source share
2 answers

Assuming ConcreteBar is a subobject

This is true since the vault was allocated for ยง3.7.5 / 1

The storage duration of member subobjects, base class subobjects, and array elements is their complete object (1.8).

and ยง3.8 / 5 states:

Before the beginning of the life of the object, but after storage, which the object will occupy, it was allocated or, after the life of the object and before storage, which the object is occupied again or freed, any pointer that refers to the storage location in which the object will be or is located can be used but only in a limited way. For an object under construction or destruction, see 12.7 [referring to the use of a non-static user]

so this is true until you use the link.

+6
source share

Yes, this is true, because as long as _bar is not yet constructed, a repository exists for it, and the link to it is fine, until you actually use this link until the body of the constructor of the derived class.

Here is another post on a topic that you can find: https://stackoverflow.com/a/318829/

And finally, the answer that the standard quotes is: https://stackoverflow.com/a/166778/

Before the life of the object, but after storage which will occupy the object, [...] was allocated, any pointer that refers to the location of the storage where the object will be or is located can be used, but only in a limited way.

+6
source share

All Articles