virtual functions are dynamically bound , but default parameters are statically bound.
class Shape {
public:
enum ShapColor (Red, Green, Blue);
virtual void draw(ShapeColor color = Red) const = 0;
};
class Rectangle: public Shape {
public:
virtual void draw(ShapeColor color = Green) const;
};
Shape *pr = new Rectangle;
the default parameter value for this function call is taken from the Shape class, not the Rectangle class!
avoid confusion
I.
class Shape {
public:
enum ShapColor (Red, Green, Blue);
virtual void draw(ShapeColor color = Red) const = 0;
};
class Rectangle: public Shape {
public:
virtual void draw(ShapeColor color = Red) const;
};
Shape *pr = new Rectangle;
but if the default paramter value is changed in Shape, all derived classes that repeat it most also be changed.
II. NVI idiom(non-virtual interface )
class Shape{
public:
enum ShapeColor{ Red, Green, Blue };
void draw(ShapeColor color = Red) const {
doDraw(color);
}
private:
virtual void doDraw(color) const = 0;
};
class Rectangle: public Shape {
public:
private:
virtual void doDraw(ShapeColor color) const;
};