Reputation: 163
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
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
B
constructor calledA
default constructor called as part of the initialization of the B
objectB
constructor is enteredA
non-default constructor called (with argument 5
) as part of creation of the temporary objectB
constructor exitsUpvotes: 6