Reputation:
I don't understand how the derived class gets its base class
class cl
{
protected:
int fe;
};
class lc : cl
{
public:
fe = 10; //How can lc access cl? I know its a base class, but how is it stored?
};
How does lc get cl's members?
Upvotes: 0
Views: 91
Reputation: 104524
Unless you are doing something special, declare your derived class as having public inheritance. Otherwise, C++ defaults to private inheritance and blocks methods in the child class from having access to the parent class's members. That is:
class lc : public cl
{
};
Also, this line won't compile as you have it inside the declaration of the child class.
fe = 10; //How can lc access cl? I know its a base class, but how is it stored?
Do this instead. initialize fe
in your constructor:
class lc : public cl
{
public:
lc() : fe(10)
{
}
};
Or just do something like this after doing the public inheritance fix above:
lc item;
item.fe = 10;
As to your "how does it work?" question. Implementation details are not usually not a part of the C++ standard, but the most likely implementation is this. Under the hood, the compiler silently decorates your child class declaration with all the same members of the parent class. As if you had copied the original class declaration, renamed it, and manually added all the new members yourself directly below the original parent members. That's what enables you to say item.fe = 10
above, even though fe
wasn't declared as a member of lc
.
Upvotes: 1