From 35144760809f15a08633d66f1fe8767a0f3e28c2 Mon Sep 17 00:00:00 2001 From: Jidong Xiao Date: Mon, 14 Apr 2025 19:05:39 -0400 Subject: [PATCH] show the importance of member initializer lists --- lectures/25_inheritance/README.md | 8 ++++++++ lectures/25_inheritance/constructor_test1.cpp | 18 ++++++++++++++++++ lectures/25_inheritance/constructor_test2.cpp | 19 +++++++++++++++++++ 3 files changed, 45 insertions(+) create mode 100644 lectures/25_inheritance/constructor_test1.cpp create mode 100644 lectures/25_inheritance/constructor_test2.cpp diff --git a/lectures/25_inheritance/README.md b/lectures/25_inheritance/README.md index 3c4a1ff..b2261ed 100644 --- a/lectures/25_inheritance/README.md +++ b/lectures/25_inheritance/README.md @@ -157,6 +157,14 @@ public: }; ``` +### Common Pitfall: + +- Member initializer lists play an important role in inheritance in C++. + +- If you try to initialize the base class inside the constructor body (not the initializer list), it won’t work — the base class has already been default-constructed by that point! This is way, for the following two programs: + +[program1](constructor_test1.cpp) will compile; but [program2](constructor_test2.cpp) won't compile. + ## 25.6 Name Hiding In C++, when a derived class defines a member function with the same name as one in its base class, the derived class's function hides all base class functions with that name, regardless of their signatures. This behavior is known as name hiding. diff --git a/lectures/25_inheritance/constructor_test1.cpp b/lectures/25_inheritance/constructor_test1.cpp new file mode 100644 index 0000000..0aba55c --- /dev/null +++ b/lectures/25_inheritance/constructor_test1.cpp @@ -0,0 +1,18 @@ +#include + +class Base { +public: + Base(int x) { + std::cout << "Base constructor: " << x << std::endl; + } +}; + +class Derived : public Base { +public: + Derived(int x) : Base(x) { // member initializer list calls Base constructor + std::cout << "Derived constructor" << std::endl; + } +}; + +int main(){ +} diff --git a/lectures/25_inheritance/constructor_test2.cpp b/lectures/25_inheritance/constructor_test2.cpp new file mode 100644 index 0000000..9c95d68 --- /dev/null +++ b/lectures/25_inheritance/constructor_test2.cpp @@ -0,0 +1,19 @@ +#include + +class Base { +public: + Base(int x) { + std::cout << "Base constructor: " << x << std::endl; + } +}; + +class Derived : public Base { +public: + Derived(int x) { // member initializer list calls Base constructor + Base(x); + std::cout << "Derived constructor" << std::endl; + } +}; + +int main(){ +}