Reputation: 34215
Given an abstract base class with a protected member, how can I provide read access only to derived classes?
To illustrate my intention I provide a minimal example. This is the base class.
class Base
{
public:
virtual ~Base() = 0;
void Foo()
{
Readonly = 42;
}
protected:
int Readonly; // insert the magic here
};
This is the derived class.
class Derived : public Base
{
void Function()
{
cout << Readonly << endl; // this should work
Readonly = 43; // but this should fail
}
};
Unfortunately I cannot use a const
member since it have to be modifiable by the base class. How can I produce the intended behavior?
Upvotes: 1
Views: 887
Reputation: 1
Best-practice guidelines for inheritance should be to always make member variables private and accessor functions public. If you have public functions that you only want called from derived classes it means you are writing spaghetti code. (source: Meyer's Effective C++ item 22)
Upvotes: 0
Reputation: 15079
The usual way to do it is to make your member private
in the base class, and provide a protected
accessor:
class Base
{
public:
virtual ~Base() = 0;
void Foo()
{
m_Readonly = 42;
}
protected:
int Readonly() const { return m_Readonly; }
private:
int m_Readonly;
};
Upvotes: 8
Reputation: 9929
As protected member is visible in derived class, if you want the member to be readonly in derived class, you can make it private, and provide a getter function.
class Base {
public:
Base();
virtual Base();
public:
int getValue() {return value;}
private:
int value;
}
This way you can still change the value in base class, and it's readonly in children class.
Upvotes: 4