Home > Net >  How do I set the parameter of a parents class's constructor in a child class?
How do I set the parameter of a parents class's constructor in a child class?

Time:08-30

In calling Parent's constructor from Child's constructor, how do I first instantiate a AnotherClass instance based on myString below, then pass in that AnotherClass instance to Parent's constructor? If that's not possible, what is a common pattern to achieve this in C ?

class Parent {
   public Parent(AnotherClass myClass){
      //....
   }
}

class Child : public Parent{
  public Child (std::string myString) : Parent (// get a AnotherClass instance by passing in myString and use that instance as input to Parent constructor) {}
}

class AnotherClass{
  public AnotherClass(std::string myString){
    ///
  }
}

CodePudding user response:

Easy solution: just do nothing. Compiler does it for you (as written in comments), as long as it's not an explicit ctor for AnotherClass:

class Child : public Parent
{
  public Child(std::string myString)
  : Parent(myString) {}
};

You can even consider simply using the ctor of Parent (by simply writing using Parent::Parent), albeit that changes the interface.

If you'd like to be verbose, you might say (again, as in the comments):

class Child : public Parent
{
  public Child(std::string myString)
  : Parent(AnotherClass(myString)) {}
};

These are for simple cases. However, sometimes you need to solve a more complicated issue before calling Parent's ctor: e.g., you'd like to reuse AnotherClass or do some calculation/verification on it. This is why I wrote the answer: in the generic case, you might need to do some arbitrary complex calculation. You might still do that, with the help of lambdas (or static member functions, or even free functions):

class Child : public Parent
{
  public Child(std::string myString)
  : Parent([&](){
    // here you can write any code
    // it'll run _before_ Parent's ctor
    AnotherClass ac(myString);
    // do any calculation on ac, store it, etc.
    return ac;
  }()) {}
};

Also, suggest using std::move when you pass the argument (unless, of course, when you need it in another place in the ctor as well).

  •  Tags:  
  • c
  • Related