Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Notice that the Derived class constructor has ii as its first argument, but the argument passed to Base was made equal to i on purpose.

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()
{

}
like image 959
Ayrosa Avatar asked Dec 28 '22 11:12

Ayrosa


1 Answers

Because i is a member variable inherited from Base, so it is defined. You can freely access member variables in initialiser lists, but what you're doing is accessing a variable before it's initialised, which is, I believe, Undefined Behaviour.

like image 196
Seth Carnegie Avatar answered Feb 01 '23 23:02

Seth Carnegie