devxlogo

Never Change the Default Parameters of Virtual Methods

Never Change the Default Parameters of Virtual Methods

It’s not a good idea to change the default parameters of virtual methods because the default parameters are bound at compile time (static binding), whereas virtual methods themselves get bound only at run time (late binding). Here’s an example:

class Base{  public:    virtual void foo(int i=0){ printf("%d",i); }}class Derived: public Base{  public:    virtual void foo(int i=10){ printf("%d",i);}}main(){  Base *pBase = new Derived();  pBase->foo();}

The expected output, based on the rules of virtual methods would be 10, because the Base pointer is pointing to the Derived object. However, because the default parameters are bound at compile time, they are bound assuming that pBase is a pointer to Base?and not to the Derived object, as is the case. Hence, the output is 0.

devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist