Please excuse my English skills; as I'm not a native speaker.
i got this code from my college textbook and im having trouble understanding it for hours...
#include<iostream>
using namespace std;
class base{
int a;
protected:
void seta(int a){this->a=a;}
public:
void showa(){cout<<a;}
};
class derived: private base{
int b;
protected:
void setb(int b){this->b=b;}
public:
void showb(){
seta(5); //1
showa(); //2
cout<<b;
}
};
class grandderived: private derived{
int c;
protected:
void setab(int x){
seta(x); //3
showa(); //4
setb(x); //5
}
};
int main(){
return 0;
}
here are my understandings so far:
class derived inherits class base as private, so everything inside class base are private. afaik private members cannot be accessed from subclasses.
so, number 1, 2 wont work.
class grandderived also inherits class derived as private, therefore 3,4, and 5 will also not work for the same reason.
but the answer tells me only number 3 and 4 wont work, and others will work. i compiled it and yes it tells me the same.
am i misunderstanding something about how the inheritance works, or are there other things that i dont know of?
I believe this is what's happening:
The base class declared seta and showa as protected and public. This means they are accessible to subclasses.
derived inherits from base. This means it has access to everything protected and public from base, which includes seta and showa. The fact that it privately inherits base means that inherited members will be marked as private, and thus cannot be accessed in classes subclassing derived (i.e. grandderived).
This same pattern occurs between derived and grandderived.
Therefore: derived can access the methods from base, and grandderived can access the methods from derived, but NOT base.
You're close.
grandderived inherits from derived and marks it as private. However, this means that the methods that has inherited from derived will not be accessible from classes inheriting from grandderived. In the same way, derived inherits from base, marking it as private.
The effect is that grandderived can access the methods of derived but not base.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With