0

Here is a class:

class P1{
public:
    P1(int i){}
};

Here is another class:

class P2{
public:
    P2(int i){}
};

Here is a class that inherits from the two classes above:

class D: public P1, public P2{
    //?
};  

Did I inheirt the constructors of the two classes as well?
How can I edit class D, so that I can construct the derived class in the following way:

D d(11,22);
Trevor Hickey
  • 36,288
  • 32
  • 162
  • 271
  • 1
    No, you did not ___inherit___ the constructors. But you can ___access___ the base class constructors. – Hindol Sep 28 '12 at 06:24
  • What you need is a [Member Initalizer list](http://stackoverflow.com/questions/1711990/what-is-this-weird-colon-member-syntax-in-the-constructor). – Alok Save Sep 28 '12 at 06:26
  • 1
    class P1: instead of A do you mean P1? – spin_eight Sep 28 '12 at 06:26
  • @spin_eight Of course he did. It's a typo. – Hindol Sep 28 '12 at 06:27
  • 1
    You can [***inherit*** constructors](http://www.stroustrup.com/C++11FAQ.html#inheriting) with the new *tricks* of C++11. But in your case i wonder if it's possible because both base class constructors have the same signature. – PaperBirdMaster Sep 28 '12 at 06:41

3 Answers3

3
class D : public P1, public P2
{
    public:
       D(int x, int y) : P1(x), P2(y) 
       {
       }
};
Jagannath
  • 3,995
  • 26
  • 30
2

This is the way to do it,

class D: public P1, public P2{
    D(int x, int y) // Have your own constructor for the derived class
        : P1(x), P2(y) {}
};
Hindol
  • 2,924
  • 2
  • 28
  • 41
1

Constructors can`t be implicitly inherited. But to be able to use base class constructors use member initialization syntax as already proposed in the prevoius answers

spin_eight
  • 3,925
  • 10
  • 39
  • 61