FAQ 17.05 How can a base class protect derived classes so that changes to the base class will not affect them?
The
A class hierarchy is more resilient to changes if it has two distinct interfaces for two distinct sets of users.
Both interfaces must be fully specified. For instance, the actual raw data of a class could be
private:
with a set of
protected: inline
member functions for accessing this data. These
inline
member functions define an interface between the derived classes and the raw bits of the base class. Then the
private:
data of the base class could be changed within reasonable bounds without
For example, suppose class
Base
has an
int
data member.
Base
can ensure that derived classes do not rely on the specific data structure by making the data structure
private:
(in this case, a simple
int
) and defining
inline protected:
class Base {
public:
Base() throw();
protected:
void storeValue(int value) throw();
int retrieveValue() const throw();
private:
int value_;
};
inline Base::Base() throw() : value_(37) { }
inline void Base::storeValue(int value) throw() { value_ = value; }
inline int Base::retrieveValue() const throw() { return value_; }
class Derived : public Base {
public:
void f(int i) throw();
};
void Derived::f(int i) throw() { storeValue(i); }
int main()
{
Derived d;
d.f(42);
}
|
FAQ 17.06 Can a derived class pointer be converted into a pointer to its public base class?Such conversions are possible and don't even require a pointer cast.
A
class Vehicle { };
class Car : public Vehicle { };
void f(Vehicle* v) throw();
void g(Car* c) throw()
{
f(c); //Perfectly safe; no cast needed
}
|
FAQ 17.07 How can a class
Y
be a
|
FAQ 17.08 How can a class
Y
get the bits of an existing class
X
without making
Y
a
|