Dipro Sen
Dipro Sen

Reputation: 4670

child class hides parent class's constructor

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.

Upvotes: 1

Views: 682

Answers (4)

jogojapan
jogojapan

Reputation: 69967

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.

Upvotes: 3

Aesthete
Aesthete

Reputation: 18850

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);

Upvotes: 1

user257111
user257111

Reputation:

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*)

Upvotes: 0

Lyubomir Vasilev
Lyubomir Vasilev

Reputation: 3030

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)
{
}

Upvotes: 0

Related Questions