OrenIshShalom
OrenIshShalom

Reputation: 7102

Implicitly passing parameter(s) to base constructor C++

I'm interested in the exact same question asked here, but for C++. Is there any way to implicitly pass parameters to a base class constructor? Here is a small example I've tried which doesn't work. When I remove the comments and call the base class constructor explicitly, everything works fine.

struct Time { int day; int month; };
class Base {
public:
    Time time;
    Base(Time *in_time)
    {
        time.day   = in_time->day;
        time.month = in_time->month;
    }
};
class Derived : public Base {
public:
    int hour;
    // Derived(Time *t) : Base(t) {}
};
int main(int argc, char **argv)
{
    Time t = {30,7};
    Derived d(&t);
    return 0;
}

Here is the complete compilation line + compilation error if it helps:

$ g++ -o main main.cpp
main.cpp: In function ‘int main(int, char**)’:
main.cpp:19:14: error: no matching function for call to ‘Derived::Derived(Time*)’
  Derived d(&t);
              ^

Upvotes: 3

Views: 270

Answers (2)

lubgr
lubgr

Reputation: 38267

You can bring all base class constructors into the scope of the subclass like this

class Derived : public Base {
  public:
    using Base::Base;

  /* ... */
};

which allows for exactly the usage scenario

Time t = {30,7};
Derived d(&t);

Note that using Base::Base always ships all constructors declared by Base. There is no way of omitting one or more.

Upvotes: 2

Some programmer dude
Some programmer dude

Reputation: 409166

You can do it by pulling in the Base class constructors into the scope of the Derived class:

class Derived : public Base
{
public:
    using Base::Base;  // Pull in the Base constructors

    // Rest of class...
};

On an unrelated note, I really recommend against using pointers. In this case it's simply not needed at all. Pass by value instead. That will make your Base constructor even simpler:

Base(Time in_time)
    : time(in_time)
{}

Upvotes: 2

Related Questions