show the importance of member initializer lists
This commit is contained in:
committed by
JamesFlare1212
parent
58b8a67d55
commit
3514476080
@@ -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.
|
||||
|
||||
18
lectures/25_inheritance/constructor_test1.cpp
Normal file
18
lectures/25_inheritance/constructor_test1.cpp
Normal file
@@ -0,0 +1,18 @@
|
||||
#include <iostream>
|
||||
|
||||
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(){
|
||||
}
|
||||
19
lectures/25_inheritance/constructor_test2.cpp
Normal file
19
lectures/25_inheritance/constructor_test2.cpp
Normal file
@@ -0,0 +1,19 @@
|
||||
#include <iostream>
|
||||
|
||||
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(){
|
||||
}
|
||||
Reference in New Issue
Block a user