Reputation: 103
I have a base class called "Grandparent" with a special protected member variable like:
class Grandparent
{
protected:
MyClass m_obj;
}
I have a class "Parent" that derives from this and monitors access to the m_obj member variable with special getters and setters:
class Parent : Grandparent
{
protected:
void setObj(val) { m_obj = val; }
MyClass getObj { return val; }
}
Finally, I have a class "Child" that inherits from Parent and uses those setObj and getObj methods in Parent:
class Child : Parent
{
//some other methods that call getObj and setObj
}
My issue is, I want to force the Child class to use the getters and setters in the Parent class, rather than being able to access the m_obj variable in the Grandparent class directly. I do not have privileges to edit the Grandparent class, only the Parent and Child classes. How do I do this?
Upvotes: 0
Views: 502
Reputation: 103
MatG's comment about searching "c++ inheritance change member access specifier" answered by question. I didn't realize you could change the access modifier of a parent class member in a derived class.
class Parent : Grandparent
{
protected:
void setObj(val) { m_obj = val; }
MyClass getObj { return val; }
private:
using Grandparent::m_obj;
}
Upvotes: 4
Reputation: 3465
How about changing the current Parent
is-a Grandparent
relationship to Parent
has-a Grandparent
one? You would have the options of Composition or Private Inheritance to choose from but given that you're having an inheritance between Parent
and Grandparent
currently and that m_obj
is a protected member of Grandparent
, I'd gather it would be more convenient to just switch to Private Inheritance since you'd still have access to all the public/protected functions/data of the Grandparent
class as it is. Now with this change, since m_obj
would become a private
member of Parent
, Child
wouldn't have access to it, and using setters/getters would be the only option for the Child
to use.
Upvotes: 0