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.