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
?
// As base-class pointer cannot access the derived class variable.
The base class members can be accessed by its sub-classes through access specifiers. There are three types of access specifies. They are public, private and protected. When the base class is publicly inherited, the public members of the base class become the derived class public members.
This is really simple, you just have to call the constructor of parent class inside the constructor of child class and then the object of a child class can access the methods and attributes of the parent class.
Private members can only be accessed by member functions of the same class or friends. This means derived classes can not access private members of the base class directly!
B
is an A
, so creating an instance of B
is creating an instance of A
. That being said, I'm not sure what your actual question is, so here's some code that will hopefully clarify things:
class A
{
protected:
int x;
};
class B : public A
{
public:
int y;
int gety() const { return y; }
void sety(int d) { y = d; }
int getx() const { return x; }
void setx(int d) { x = d; }
};
int main()
{
B obj;
// compiles cleanly because B::sety/gety are public
obj.sety(10);
std::cout << obj.gety() << '\n';
// compiles cleanly because B::setx/getx are public, even though
// they touch A::x which is protected
obj.setx(42);
std::cout << obj.getx() << '\n';
// compiles cleanly because B::y is public
obj.y = 20;
std::cout << obj.y << '\n';
// compilation errors because A::x is protected
obj.x = 84;
std::cout << obj.x << '\n';
}
obj
can access A::x
just as an instance of A
could, because obj
is implicitly an instance of A
.
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