0

I am trying to accomplish the following: I have 4 classes(lets call one primary, other 3 secondary ones) within one namespace, I want to store instances of secondary classes as private members of primary, to do this I need to call secondary constructors from primary's one and then store instances. But Unfortunately I do not completely understand how to do it (not really experienced with c++): here is what I have in header file:

    class secondary_one
    {
    private:
        int number1;
    public:
        secondary_one(int);
        int get_number1() const;
    };

    class secondary_two
    {
    private:
        int number2;
    public:
        secondary_two(int);
        int get_number2() const;
    };

    class secondary_three
    {
    private:
        int number3;
    public:
        secondary_three(int);
        int get_number3() const;
    };

And 'primary' class is:

class primary
{
private:
    secondary_one one;
    secondary_two two;
    secondary_three three;
public:
    primary(int,int,int);
};

Upon calling primary constructor I want first argument to be send to constructor of secondary_one, second argument to constructor of secondary_two and so on. And then store instances as private members. Is it even possible or I am just wasting time? If it is, can you give a short example what should I have in header and source file?

1 Answer 1

5

Use the constructor initialization list:

class primary
{
public:
  primary(int a, int b, int c) : one(a), two(b), three(c) {}
private:
    secondary_one one;
    secondary_two two;
    secondary_three three;
};
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.