How do I change the protected values โโof a base class variable in a derived class function?
class abc{
protected:
int x;
};
class b: public abc{
public :
void something(abc a){ a.x = 1;}
};
I am getting an error on the second last line, which says that I cannot access the x member of the variable a.
Error: The protected member "abc :: x" is not accessible through a dot or object "abc".
Is there any other way to change the x value of the variable a?
source to share
Inheritance b
may change the values โโof the base class "it" is inherited, but the base class attributes of abc
other objects are still protected and reserved for themselves. In this case, the object abc
a
that you pass through the function something
is another object, not related to the object b
.
Access modifiers work at the class level, that is b
, the private attributes of another object can be accessed on an object b
. However, this inheritance shown basically says " b
is abc
, but abc
not necessarily b
". In a function void something(abc a){ a.x = 1;}
, if you change it to something(b a)
, it will work because it b
can access another b
.
However, remember that if:
int main(){
abc data;
abc data2;
data.x = data2.x; //This won't work becuase you are outside the class
}
What you can do is declare class to a b
friend of the class abc
so that any object b
can access the protected members of any other object abc
.
Example:
class abc{
protected:
int x;
friend class b;
};
source to share
Internally, something()
you are in the scope of an object, so you have a pointer to the current object with the keyword this
. However, in C ++, the default permission in object scope is the object's own scope, so you don't need to prefix it. A simple reference to the property name is sufficient for the resolution to be successful.
source to share
One way to do what you are asking is to have a setX () function in the ABC class, for example:
class abc
{
public:
void setX(int x){ this->x = x; }
protected:
int x;
};
Then declare something
inside class B like this:
class b: public abc
{
public :
void something(abc a){ a.setX(1); }
};
At this point, although you may not have class B at all, but rather from the scope you are calling b.something(myABCObj)
, just call myABCObj.setX(1)
.
The point of "protected" is that it class b
has access to "x" class abc
not through the parameter you pass, but rather within itself .
For example, your class b might look like:
class b: public abc{
public :
void something(){ x = 1; } //HA- I inherited a value from class abc that wasn't public and changed it!
};
So, in a different scope, it is possible to create an object b myB;
, and myB.x
will not be allowed, but myB
will have access to the 'x' internally from its parent class.
source to share