I have a simple class as below
class A {
protected:
int x;
};
class B:public A
{
public:
int y;
void sety(int d)
{
y=d;
}
int gety(){ return y;}
};
int main()
{
B obj;
obj.sety(10);
cout<<obj.gety();
getch();
}
How can I set the value of the protected
instance variable A::x
from an instance of the derived class B
without creating an instance of class A
.
EDIT: Can we access the value of A::x
using the object of B? Like obj.x
?
B
is anA
, so creating an instance ofB
is creating an instance ofA
. That being said, I'm not sure what your actual question is, so here's some code that will hopefully clarify things:obj
can accessA::x
just as an instance ofA
could, becauseobj
is implicitly an instance ofA
.You can just refer to it simply as
x
in class BFor example:
A::x
is protected, so not accessible from outside, neither asA().x
orB().x
. It is however accessible in methods ofA
and those directly inheriting it (because protected, not private), e.g.B
. So, regardless of semanticsB::sety()
may access it (as plainx
or asA::x
in case of shadowing by aB::x
or for pure verbosity).Note that B does not have FULL access to A::x. It can only access that member through an instance of a B, not anything of type A or deriving from A.
There is a workaround you can put in:
and now using getX, a class derived from A (like B) can get to the x member of ANY A-class.
You also know that friendship is not transitive or inherited. The same "workaround" can be made for these situations by providing access functions.
And in your case you can actually provide "public" access to the x through your B by having public functions that get to it. Of course in real programming it's protected for a reason and you don't want to give everything full access, but you can.