Why doesn't the compiler complain about the Derived class constructor definition?

Note that the Derived constructor has ii as its first argument, but the argument passed to Base was specifically chosen by i .

 class Base { protected: int i; public: Base(int i) : i(i) {} }; class Derived : public Base { private: int k; public: Derived(int ii, int k) : Base(i), k(k) {} // Why not C2065: 'i' undeclared identifier }; int main() { } 
+4
source share
2 answers

Because i is a member variable inherited from Base , so it is defined . You can freely access member variables in initialization lists, but what you do is access the variable before initializing it, which I consider to be Undefined Behavior.

+7
source

Because he sees i from the base class and uses it in the initializer. If you change the protection to confidential, you will receive a Base::i error message.

+3
source

Source: https://habr.com/ru/post/1381015/


All Articles