Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Home » Tip Bank » C++
Language: C++
Expertise: Advanced
Feb 8, 2006

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.

C.V. Ram Narayanan Sastry
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date