4. Delegating and Inheriting Constructors
Content available in the full version of the book.
Limitations
Content available in the full version of the book.
Inheritance
Content available in the full version of the book.
Inheriting constructors
In our previous example with DebugPropertyInfo we didn’t have any new data members, only some new member functions. The code showed a single constructor called the base class constructor. Since C++11, you can tell the compiler to “reuse” the code:
1 class DebugDataPacket : public DataPacket {
2 public:
3 using DataPacket::DataPacket;
4
5 void DebugPrint(std::ostream& os) {
6 os << getData() << ", " << getCheckSum() << '\n';
7 }
8 };
9
10 int main() {
11 DebugDataPacket hello{"hello!", 404};
12 hello.DebugPrint(std::cout);
13 }
Consider line 3 - using DataPacket::DataPacket;. This tells the compiler that it can use all constructors from the base class, ignoring access modifiers. It means that all public constructors are visible and can be called, but the protected will still be protected in that context. Still, if you want to limit the access to constructors, you must explicitly write constructors for DebugDataPacket.
We completed all information about constructors, but it’s good to mention one more thing: destructors. See in the next chapter.