I have these classes:
class Base
{
public:
virtual void foo(int x = 0)
{
printf("X = %d", x);
}
};
class Derived : public Base
{
public:
virtual void foo(int x = 1)
{
printf("X = %d", x);
}
};
When I have:
Base* bar = new Derived();
bar->foo();
My output is "X = 0", even if foo is called from Derived, but when I have:
Derived* bar = new Derived();
bar->foo();
My output is "X = 1". Is this behavior correct? (To select default parameter value from the declaration type, instead of selecting it from actual object type). Does this break C++ polymorphism?
It can cause many problems if somebody uses virtual functions without specifying the actual function parameter and uses the function's default parameter.
C allows functions with a variable number of arguments (called variadic functions) through the use of a set of macros defined in the stdarg. h header: va_start() , va_copy() , va_arg() and va_end() that allow you to scan the list of 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.
Default Arguments in C++ A default argument is a value provided in a function declaration that is automatically assigned by the compiler if the calling function doesn't provide a value for the argument. In case any value is passed, the default value is overridden.
How Does __init__() Method Work? The python __init__ method is declared within a class and is used to initialize the attributes of an object as soon as the object is formed. While giving the definition for an __init__(self) method, a default parameter, named 'self' is always passed in its argument.
Default arguments are retained even if you override a function! And this behaviour is correct. Let me search the reference from the C++ Standard.
§8.3.6/10 [Default arguments] from the C++ Standard says,
A virtual function call (10.3) uses the default arguments in the declaration of the virtual function determined by the static type of the pointer or reference denoting the object. An overriding function in a derived class does not acquire default arguments from the function it overrides.
The example from the Standard itself
struct A {
virtual void f(int a = 7);
};
struct B : public A {
void f(int a);
};
void m()
{
B* pb = new B;
A* pa = pb;
pa->f(); //OK, calls pa->B::f(7)
pb->f(); //error: wrong number of arguments for B::f()
}
Also, not only it's retained, it is evaluated everytime the function is called:
§8.3.6/9 says,
Default arguments are evaluated each time the function is called
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With