If I make a constructor for Class A, and then decide to make a new class B inherit from A, will I have to write a new constructor for it, complete with the original (plus any new ones) parameters?
#include <iostream>
usingnamespace std;
class A
{
public:
int a1;
int a2;
A(int a1_, int a2_):
a1(a1_),a2(a2_){}
};
class B: public A
{
public:
int b1;
int b2;
B(int a1_,int a2_,
int b1_, int b2_):
A(a1_,a2_),
b1(b1_),b2(b2_){}
};
int main()
{
B b(1,2,3,4);
cout << b.a1 << endl;
cout << b.a2 << endl;
cout << b.b1 << endl;
cout << b.b2 << endl;
cin.get();
return 0;
}
Ah excellent... So, I do that In the Definition of A's Constructor, not in the parameter list I guess?
You do it in B's ctor-initializer:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
class A
{
int i;
public:
A(int i): i(i) {}
};
class B
{
public:
B(): A(0){} // default call A with zero as parameter
B(int i): A(i){} // or pass the parameter to B up to A's constructor
};