Initializer list question.

I am trying to define a Composite class.
A component needs a constructor parameter. How to initialize the component?
Below is my attempt, but it gets a compile error on line 18.

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
#include <iostream>

class Component
{
    private:
        int var;
    public:
        Component(int var): var(var) {}
        virtual void print() { std::cout << var << std::endl; }
};

class Composite
{
    private:
        Component component;
    public:
        Composite()
            : component(component(3))  // error: no match for call to ‘(Component) (int)’
        { }
        virtual void printComponent() { component.print(); }
};

Composite composite;

int main()
{
    composite.printComponent();
}


Thank you.
Last edited on
Hi,

Try this :+)

16
17
18
19
public:
        Composite()
            : component(3)  
        { }


Edit:

If you are going to have virtual functions, you will need virtual destructors. virtual functions are normally used to make an interface in the base class. Not sure whether you knew that already :+)
Last edited on
Thanks TheIdeasMan! That worked.
Topic archived. No new replies allowed.