Simple and Quick question.

Yeah, I've only got a simple question...

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?
Last edited on
You have to write a new constructor for B. It can have any parameters you want as long as it calls one of A's constructors.
Ah excellent... So, I do that In the Definition of A's Constructor, not in the parameter list I guess?

Or would that be possible.. Hmm..

Code example? :D
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include <iostream>
using namespace 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;
}
AngelHoof wrote:
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
};
Topic archived. No new replies allowed.