16

Assume class Child is a derived class of the class Parent. In a five file program, how would I specify in Child.h that I want to call the constructor of Parent? I don't think something like the following is legal inside the header:

Child(int Param, int ParamTwo) : Parent(Param);

In this situation, what should Child.cpp's constructor syntax look like?

Wolf
  • 9,679
  • 7
  • 62
  • 108
user3658679
  • 329
  • 1
  • 2
  • 8
  • Possible duplicate http://stackoverflow.com/questions/120876/c-superclass-constructor-calling-rules ? – quantdev Jun 04 '14 at 20:49

2 Answers2

34

In Child.h, you would simply declare:

Child(int Param, int ParamTwo);

In Child.cpp, you would then have:

Child::Child(int Param, int ParamTwo) : Parent(Param) {
    //rest of constructor here
}
πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
wolfPack88
  • 4,163
  • 4
  • 32
  • 47
12

The initialization list of a constructor is part of its definition. You can either define it inline in your class declaration

class Child : public Parent {
    // ...
    Child(int Param, int ParamTwo) : Parent(Param)
    { /* Note the body */ }
};

or just declare it

class Child : public Parent {
    // ...
    Child(int Param, int ParamTwo);
};

and define in the compilation unit (Child.cpp)

Child::Child(int Param, int ParamTwo) : Parent(Param) {
}
πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190