mercredi 5 août 2015

Inheriting constructors w / wo their default arguments?

C++ Primer (5th edition) on page 629 states:

  • If a base class constructor has default arguments, those arguments are not inherited.

I tried this for myself and to me it seems that the derived constructor generated by the compiler also has the same default arguments as the base constructor.

Here's a little test:

#include <iostream>

struct Base
{
    Base() = default;

    Base(int x_, int y_ = 88, int z_ = 99)
        : x(x_), y(y_), z(z_) {}

    virtual void debug() const 
    { std::cout << "\nx - " << x << ", y - " << y << ", z - " << z << '\n'; } 

private:
    int x, y, z;
};

struct Derived : Base
{
    using Base::Base;
};

int main() {
    Base B(1);
    B.debug();         // x - 1, y - 88, z - 99
    Derived D(5);
    D.debug();         // x - 5, y - 88, z - 99

    return 0;
}

( You can run this here - http://ift.tt/1P60jS2 )


So are we inheriting also the default arguments for a inherited constructor or not?
If not, how come I'm not getting junk for the last 2 members but the same exact values as the default argumuments for the constructor inherited from base?
Also searched on the internet for a clear response about this but found none.

Aucun commentaire:

Enregistrer un commentaire