Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Virtual functions default parameters

Tags:

c++

Could anybody explain where c++ compilers keep default values for parameters for virtual functions? I know it is a bad idea to change these parameters in child classes but why? Thanks.

like image 580
Leaf Avatar asked Aug 07 '13 14:08

Leaf


People also ask

Can virtual functions have default arguments?

Like any other function, a virtual function can have default arguments (§ 6.5. 1, p. 236). If a call uses a default argument, the value that is used is the one defined by the static type through which the function is called.

Can virtual functions have parameters?

Yes, C++ virtual functions can have default parameters.

Why are virtual functions set 0?

It's just a syntax, nothing more than that for saying that “the function is pure virtual”. A pure virtual function is a virtual function in C++ for which we need not to write any function definition and only we have to declare it.

What are the rules for virtual function?

Rules for Virtual FunctionsVirtual functions cannot be static. A virtual function can be a friend function of another class. Virtual functions should be accessed using pointer or reference of base class type to achieve runtime polymorphism.


1 Answers

It's a bad idea because they aren't kept anywhere.

The default values that are used will be those defined in the static (compile-time) type. So if you were to change the default parameters in an override, but you called the function through a base class pointer or reference, the default values in the base would be used.

#include <iostream>  struct Base {     virtual ~Base(){ }     virtual void foo(int a=0) { std::cout << "base: " << a << std::endl; } };  struct Derived : public Base {     virtual ~Derived() { }     virtual void foo(int a=1) { std::cout << "derived: " << a << std::endl; } };  int main() {     Base* derived = new Derived();     derived->foo();    // prints "derived: 0"     delete derived; } 
like image 157
zmb Avatar answered Sep 20 '22 23:09

zmb