DarkLight
DarkLight

Reputation: 163

C++ base class constructor with default parameters

I wrote this small program to test my understanding. What I'm having trouble understanding is that constructors aren't inherited, but class B is able to call the constructor of class A!

#include <iostream>
using namespace std;

class A {
public:
    A(int x = 2) {          //Constructor A
        num = x;
    }
    int getNum() {
        return num;
    }

protected:
    int num;
};

class B: public A {         //Constructor B
public:
    B() {
        A(5);
    }
};

int main() {

    A a(3);                     //create obj a with num = 3
    B b;                        //create obj b
    cout << a.getNum() << endl;
    cout << b.getNum() << endl;
    return 0;
}

The output is:

3
2

What did the constructor A's call do exactly? It didn't use the passed argument to initialize object b's number!

Furthermore, if I remove the default value from class A's constructor, I get compilation error:

no matching function for call to 'A::A()'

So what's exactly happening here?

I know that the correct way is to do so:

class B: public A {         //Constructor B
public:
    B() : A(5) {
    }
};

Which gives the output:

3
5

But this is just for the purpose of understanding.

Upvotes: 2

Views: 4251

Answers (1)

Some programmer dude
Some programmer dude

Reputation: 409432

Lets take a look at the B constructor:

B() {
    A(5);
}

Here you actually "call" the A constructor twice. Once as part of the B construction (where the "default" A constructor is called), and once as you create a temporary object inside the B constructor body.

The sequence is as

  1. B constructor called
  2. A default constructor called as part of the initialization of the B object
  3. The body of the B constructor is entered
  4. A non-default constructor called (with argument 5) as part of creation of the temporary object
  5. The temporary object goes out of scope and is destructed
  6. The body of the B constructor exits

Upvotes: 6

Related Questions