-3

If I understand correctly, the base class constructor is always called with creating an object of the derived class. Is there a way to call an overloaded base class constructor when creating the derived object?

user2079828
  • 645
  • 1
  • 8
  • 31
  • 6
    Are you familiar with constructor initializer lists at all? – Kerrek SB Jul 05 '13 at 15:55
  • 5
    Use constuctor's initialization lists – Andy Prowl Jul 05 '13 at 15:55
  • Alok: Not really a dupe. This question asks "how do I do X", and the answer is "use Y." That question asks "What is Y" but does not really elaborate on how it solves X. Reading the linked question may only serve to confuse, not clarify, until the OP knows what Y is. – John Dibling Jul 05 '13 at 15:58
  • Thank you. I was not familiar with it, but I will be soon. I tried searching for this answer, but could not quite find what I was looking for. Sorry. – user2079828 Jul 05 '13 at 16:14
  • Voting to reopen for reasons I elaborated above. – John Dibling Jul 05 '13 at 16:18

1 Answers1

6

Yes, via an initialization list:

class Base
{
public:
  Base (int n) : mN(n) {}
private:
  int mN;
};

class Derived : public Base
{
public:
  Derived() : Base (42) {};
         // ^^^^^^^^^^^    
         // Initialization List
};

For more about the initialization list syntax, see this question:

What is this weird colon-member (" : ") syntax in the constructor?

Community
  • 1
  • 1
John Dibling
  • 99,718
  • 31
  • 186
  • 324