I think what would be better would be better to give or deny inherited
classes that capability. Something like the following:
struct base_class
{
private:
int x;
friendstruct NeedsX;
};
struct class_A : public base_class
{
void test() { x = 3; } // Compile error
};
struct NeedsX
{
void setState(base_class &b) { b.x = 3; }
};
// This class can manipulate the base class "state"
struct class_B : public base_class, public NeedsX
{
void test() { setState(*this); }
};- Hide quoted text -
- Show quoted text -
I have a follow on question to this. Consider
class base {
public :
virtual int read ( /* arguments */ ) = 0 ;
virtual int write ( /* arguments */ ) = 0 ;
};
class derived_1 : public base {
public :
int read ( /* arguments */ ) { return whatever ; }
int write( /* arguments */ ) { return whatever ; }
};
class derived_2 : public base {
public :
int read ( /* arguments */ ) { return whatever ; }
int write( /* arguments */ ) { return whatever ; }
};
enum { DER1, DER2, DER_LAST };
// later
typedef std::vector < base* > BASE_VEC ;
BASE_VEC bv ( DER_LAST ) ;
bv [ DER1 ] = new derived_1 ;
bv [ DER2 ] = new derived_2 ;
// now call the read or write methods through the common base
interface.
bv [ DER1 ]->read ( /*whatever*/ ) ;
bv [ DER2 ]->read ( /*whatever*/ ) ;
Now that was yesterday. Today I realized I need to extend derived_2's
_and_ only derived_2's interface. The only way do this while
maintaining a vector of base pointers is to add virtual methods to
Base.
So now:
class base {
public :
virtual int read ( /* arguments */ ) = 0 ;
virtual int write ( /* arguments */ ) = 0 ;
//lots of stuff added here that _only_ derived 2 cares about
virtual void set_pitch_command ( /*arguments*/) { /* do
nothing* / }
virtual int get_pitch_command () const { return 1; /* return
anything*/ }
virtual void set_pitch_reference ( /*arguments*/) { /* do
nothing* / }
virtual int get_pitch_reference () const { return 1; /* return
anything*/ }
};
and of course derived_2 will implement the appopriate functionality.
In my view extending the base class interface with a litany of
functinos that only 1 dervied class cares about just seem wrong and
suggests time for a redesign, however, I'm not sure what the right
approach is here short of abandoning the vector of base pointers.
Thoughts.
Thanks