I have a public inheritance, Derived
struct inheriting from Base
. The Base
has a data member int i
initialized to 5.
Now I have two codes.
Code 1 : Compiles fine
#include <iostream>
using namespace std;
struct Base{
int i = 5;
};
struct Derived: public Base{
int j = i; // Derived class able to use variable i from Base
Derived(){
i = 10; // Constructor of Derived able to access i from Base
}
};
int main()
{
Derived dobj;
cout << dobj.i;
return 0;
}
Code 2 : Gives error
#include <iostream>
using namespace std;
struct Base{
int i = 5;
};
struct Derived: public Base{
int j = I; //Still works
i = 10; // Error here " main.cpp:15:3: error: ‘i’ does not name a type"
i = 10;
Derived() = default;
};
int main()
{
Derived dobj;
cout<<dobj.i;
return 0;
}
Why is it that i
can be used to assign and be assigned inside constructor body (as in code 1), but not used directly in Derived
class (as in code 2). Also what does the error mean?
I was under the impression that the scope of Derived
is nested inside Base
, so shouldn't it be able to see the data members inside Base
scope?
Aucun commentaire:
Enregistrer un commentaire