C++ Calling abstract base class constructor on a child constructor [duplicate]

  base, c++, class, constructor, inheritance

I want to access the base class constructor by using child’s constructor:

struct sA {
  string name;
  virtual void doSomething() = 0;

  sA(string name) {
    this->name = name;
  }
};

struct sB : sA {
  string description;
  void doSomething();
}

...

vector<sA*> list;
list.push_back(new sB("My name"));

The code above does not allow me to access sA‘s constructor so up to now I’ve always just copy pasted the sA‘s constructor to each of its child constructor instead, like so

struct sA {
  string name;
  virtual void doSomething() = 0;
};

struct sB : sA {
  string description;

  sB(string name) {
    this->name = name;
  }

  void doSomething();
}

...

vector<sA*> list;
list.push_back(new sB("My name")); 

The code above works but produces way too much copy&paste code when I have multiple childs which basically all use same constructor. So is it possible to reduce the amount of copy&paste by basically inheriting base class constructor for the child to use?

Source: Windows Questions C++

LEAVE A COMMENT