1

I have a class C that inherits class P

template <typename T>
class P{
  public:
  P();
  P(T* sometype);
};

class C: public P<sometype>{

};

Now would C hide P(sometype*) constructor ? But I need that P(ometype*) constructor be available in C. Do I need to write another C(sometype*) that calls parent constructor ? or there is some easy breakthrough. and I don;t want to use C++11 features.

einpoklum
  • 118,144
  • 57
  • 340
  • 684
Dipro Sen
  • 4,350
  • 13
  • 37
  • 50
  • The parent class constructor creates a parent object. There's no point _inheriting_ that in a child class: its constructor should obviously create a child object. The parent class constructor is _available_, though, to create the parent object inside the child object. – MSalters Aug 20 '12 at 11:42
  • Not quite a duplicate, but very close: http://stackoverflow.com/questions/347358/inheriting-constructors – jogojapan Aug 20 '12 at 11:44
  • In C++03 that cannot be done without creating a constructor in C that will manually forward the call, in C++11 you can have inherited constructors – David Rodríguez - dribeas Aug 20 '12 at 12:20

4 Answers4

3

Yes, constructors are not inherited. You need to write a new one for C:

template <typename T>
class C : public P<T> {
public:
  C(T* sometype) { /*...*/ }
};

Note, in addition, that your use of the identifier sometype is inconsistent. In the case of P you use it as a variable name, in C it is a typename, but one that hasn't been declared.

Another question is what the constructor of C is going to do about the sometype object. I suspect it is going to do exactly what P's constructor does, and since you need to call the constructor of the base class anyway, your implementation of the C constructor will most likely look like this:

template <typename T>
class C : public P<T> {
public:
  C(T* sometype):P<T>(sometype) { }
};

As a final remark: C++11 actually offers constructor inheritance as a feature. Since you are not interested in using C++11 features (which is a pity though indeed), and since the feature is not yet implemented by many compilers I won't go into the details. The reference to the feature definition is here.

jogojapan
  • 68,383
  • 11
  • 101
  • 131
1

If you need to specify your baseclass type T through your sub-type, try this:

template<typename T>
class C : public P<T> {
  public:
    C(T* pT): P(pT) {}
}

int* pMyInt;
C<int> myClass(mMyInt);
Aesthete
  • 18,622
  • 6
  • 36
  • 45
0

You should write a constructor of C that takes the same parameter and passes it to its parent class, like this:

C(T* sometype)
    : P(sometype)
{
}
Lyubomir Vasilev
  • 3,000
  • 17
  • 24
0

Now would C hide P(sometype*) constructor ?

Yes, in the sense that C does not inherit P's constructors. So C will not have the constructor of the parent class available to users of the class.

But I need that P(ometype*) conctructor be available in C

That's possible: you simply call it directly:

P::P(sometype*)