Skip to main content
gamedev.net
🔒 Locked

virtual functions with default parameters

Started by moeron Sep 12, 2006 at 9:02 AM 3 replies 1.5k views
Original Post
moeron
moeron
I've stumbled across a minor oddity in the C++ language (or maybe it's just the MSVC 2003 implementation) yesterday. Here's an example...

#include <iostream>
#include <memory>
struct foo{
  virtual void func( char* str = "foo::func" ){
     std::cout << "entering: foo::func" << std::endl;
     std::cout << str << std::endl;
  }
};
struct bar : foo{
  virtual void func( char* str = "bar::func" ){
    std::cout << "entering: bar::func" << std::endl;
    std::cout << str << std::endl;
  }
};

int main(int,char**){
  bar baz;
  baz.func( ); 
  std::auto_ptr<foo> p( new bar );
  p->func( );
  
  return 0;
}
--Outputs--
entering bar::func
bar::func
entering bar::func
foo::func
So what I don't understand is why virtual functions determine properly which function to call - but don't determine the correct default parameters. If I declared p as a pointer to bar then it would grab the proper default parameters. It just seems to go against the whole point of virtual functions to grab the default params based on what the pointer is declared as - not on the true polymorphic type of it. Could anyone shed some light on this for me - perhaps some kind of protection this yields or something else I could be overlooking? Thanks
moe.ron
ToohrVyk
ToohrVyk
Default parameters are resolved at compile-time. When the compiler looks determines that the called function is the func function on a foo pointer, it looks at the definition of that function and determines what the default parameter is. It then transforms p->func(); into p->func("foo::func");.

In practice, this means that default parameters do not exist at runtime: they are simply a rewriting rule used when arguments are missing. The rationale behind this is to avoid creating a duplicate of the code — one with the argument and one without.

A workaround is to write the no-parameter function using the with-parameter function:

void func() { this->func("foo::func"); }
mikeman
mikeman
It's just a language glitch that causes the program to behave in a way that it shouldn't, in a relatively sane world. As with most C++ glitches there is *some* explanation(that interests more the compiler than the programmer) behind it, but at the end of the day I agree it's icky to execute one function with the default parameter values of another. It's no big deal though, you just have to live with it, that's all :)
moeron
moeron
Thanks for the responses everyone - it hadn't dawned on me that default params were compile time. That makes sense now.
moe.ron

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.