markoj
markoj

Reputation: 148

Use parameters with user defined type parameters without declaring a default parameter for that type

This is what happened (I simplified the problem to be easier to see):

#include<iostream>

class number_holder{
    public:
        int value;
        number_holder(int value_to_set){
            this->value=value_to_set;
        }
};

class number_holder_pair{
    public:
        number_holder first;
        number_holder second;
        number_holder_pair(number_holder first,number_holder second) 
        {
            this->first=first;
            this->second=second;
        }
};

I know adding number_holder(){} into the number_holder class solves the problem, but why is that needed?

Upvotes: 0

Views: 66

Answers (1)

cigien
cigien

Reputation: 60278

In this constructor:

number_holder_pair(number_holder first, number_holder second)
{  // <--
    this->first=first;
    this->second=second;
}

before reaching the marked line, all the members must be initialized. However, there is no default constructor for number_holder, and so the first and second members can't be default constructed, and the code doesn't compile.

As you've noticed, adding a default constructor:

number_holder() {}

solves this particular problem, and allows the code to compile. Note that this fix is not entirely correct, as your value member is still not initialized. Instead you should do:

int value = 0;
number_holder() = default;

However, you don't necessarily have to provide a default constructor, so long as you initialize all the number_holder members before reaching the definition of the number_holder_pair constructor:

number_holder_pair(number_holder first,number_holder second)
 : first(first), second(second) {}

This syntax is called a member-initializer-list.

Upvotes: 4

Related Questions