Another option is to create a Movable
interface (pure virtual class) that declares methods for moving, and derive subclasses that implement those methods:
Block Movable
| |
+-ColorBlock----------+-MovableColorBlock
| |
+-ImageBlock----------+-MovableImageBlock
Edit
Yeah, if the move()
method really is the same between the subclasses, then this isn't what you want.
It sounds like the move()
operation is orthagonal to the draw()
operation, which to me suggests an aggregation instead of a subclass. So let's take a slight left turn here.
A Block
has a position; perhaps the positional parameter could be what's movable or not:
class Position
{
public:
Position( int x, int y ) : m_x(x), m_y(y) { }
virtual ~Position() {}
int getX() const { return m_x; }
int getY() const { return m_y; }
virtual bool movable() const { return false; }
protected:
int m_x;
int m_y;
};
class MovablePosition : public Position
{
public:
MovablePosition( int x, int y ) : Position( x, y ) {}
virtual ~MovablePosition() {}
void move( int newX, int newY ) { m_x = newX; m_y = newY; }
virtual bool movable() const { return true; }
};
Then your base Block
class takes a Position
as a parameter:
class Block
{
public:
Block( Position *p ) : m_pos( p ) {}
virtual ~Block() {}
virtual void draw() = 0;
Position *getPos() const { return m_pos; }
protected:
Position *m_pos;
};
Then if you want to move a Block
subclass instance, you'd first check the movable()
method:
if ( myColorBlock.getPos()->movable() )
{
MovablePosition *p = myColorBlock.getPos();
p->move( newX, newY );
myColorBlock.draw();
}
No need to create redundant MovableXxxBlock
classes, no repetition of code. Under this scheme, a block's movability is established at runtime, not compile time; that may or may not be compatible with your goals.