menu

hjk41的日志

Avatar

Effective C++ 38: Never redefine an inherited default parameter value

A default parameter can exist only as part of a function. So if you want to redefine an inherited default parameter value, you have to redefine the function in which it is defined.
There are two kinds of functions: vitual functions and nonvirtual functions. It has been proven a bad idea to redefine an inherited nonvirtual function in the last Item. So we will simplify our disscussion to redefining default parameter values in virtual functions.
It is well known that virtual functions are dynamically bound, but it is not equally known that default parameter values are statically bound. So if we have two classes B and D:


class B{
    ...
    void mf(int defPara=0);
}
class D:public B{
    void mf(int defPara=1);
}


and we do this:


B * p=new D;
p->mf();


then what will be called is D::mf(0). That's because default parameter vaules are statically bound in C++ for effeciency matters.

评论已关闭