4

Let's say I have a:

class A {
    A(int i);
};

class B : A {
};

I cannot instanciate B(3) for instance, as this constructor is not defined. Is there a way to instanciate a B object that would use the A constructor, without having to add "trivial" code in all derived classes? thanks

thanks

sehe
  • 374,641
  • 47
  • 450
  • 633
lezebulon
  • 7,607
  • 11
  • 42
  • 73

3 Answers3

6

C++11 has a way:

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

class B : A {
public:
    using A::A; // use A's constructors
};
Pubby
  • 51,882
  • 13
  • 139
  • 180
2

If you're using C++03 this is the best thing I can think of in your situation:

class A {
public:
    A(int x) { ... }
};

class B : public A {
public:
    B(int x) : A(x) { ... }
}

You may also want to check out the link below, which is a C# question but contains a more detailed answer regarding why constructors can act this way:

C# - Making all derived classes call the base class constructor

Community
  • 1
  • 1
Tom
  • 2,973
  • 3
  • 28
  • 32
2

as user491704 said it should be something like this

class mother {
public:
 mother (int a)
 {}
 };

class son : public mother {
public:
 son (int a) : mother (a)
 { }
   };

Here is a link for the Tutorial

andrewmag
  • 252
  • 1
  • 4
  • 11