Home > Mobile >  Using parent constructor instead of defining child
Using parent constructor instead of defining child

Time:05-06

I have a base class Foo and two child classes Bar and Car. Foo is pure virtual. Bar inherits foo with its own constructor to assign a variable. However Car doesn't have a constructor.

#include <memory>
#include <iostream>
class Foo{
public:
    virtual void T() = 0;
};
class Bar : public Foo{
protected:
    int n;
public:
    Bar(int n){
        this->n = n;
    }
    virtual void T(){
        std::cout << n << std::endl;
    }
};
class Car : public Bar{
    void T(){
        std::cout << n << std::endl;
    }
};

int main(){
    Foo* f = new Car(10);//error
    return 0;
}

What I'd like to do essentially, is instantiate new Car but instead of writing out the constructor for Car and then calling the parents constructor

    Car(int n) : Bar(n){
        
    }

It would be so much easier if by instantiate car, because a constructor isn't explicitly defined it automatically calls the parent's constructor?

Is that possible?

CodePudding user response:

You can apply inheriting constructors as:

class Car : public Bar {
    using Bar::Bar;
    ...
};

Then

Car car(10); // Bar base subobject is initialized by Bar(10)
  •  Tags:  
  • c
  • Related