Obviously I'm not understanding constructors...

Here is my code:

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
class SubTest {
    public:
        SubTest(int i);

    private:
        int j;
};


class Test {
    public:
        Test(int i);

    private:
        SubTest sub_test;
};

Test::Test(int i) {
    sub_test = SubTest(i);
}


SubTest::SubTest(int i) {
    j = i;
}


When I compile this I get the following error:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
$ g++ -o test test.cpp 
test.cpp: In constructor ‘Test::Test(int)’:
test.cpp:18:17: error: no matching function for call to ‘SubTest::SubTest()’
 Test::Test(int i) {
                 ^
test.cpp:18:17: note: candidates are:
test.cpp:3:9: note: SubTest::SubTest(int)
         SubTest(int i);
         ^
test.cpp:3:9: note:   candidate expects 1 argument, 0 provided
test.cpp:1:7: note: SubTest::SubTest(const SubTest&)
 class SubTest {
       ^
test.cpp:1:7: note:   candidate expects 1 argument, 0 provided


I can't quite figure out what I'm doing wrong here...why is this not seeing the value I'm passing to SubTest?
I figured out the issue. The issue is that the Test class has SubTest sub_test; in it's private section which is a declaration without any parameters (by design). So to support this a constructor with no parameters is needed. Changing the SubTest declaration to the following is enough:

1
2
3
4
5
6
7
8
class SubTest {
    public:
        SubTest() {};
        SubTest(int i);

    private:
        int j;
};
Or you could have done this:
 
Test::Test(int i) : sub_test(i) { }

and there is no need for the additional constructor.
Topic archived. No new replies allowed.