Abi
Abi

Reputation: 29

C++ Error while passing enum as default parameter by reference in C++

Here's what I'm trying to accomplish:

class Schedule
{
    public:
    enum day{MON, TUE, WED, THU, FRI, SAT, SUN};
    void isWeekend(day &dayOfWeek=SUN);
}

I'm trying to retrieve the day in the function that calls isWeekend, defaulting it to 'SUN'. On VS2017, this is the error that I see:

initial value of reference to non-const must be an lvalue.

What am I missing? The same function compiles without the & i.e.

void isWeekend(day dayOfWeek=SUN)

Upvotes: 1

Views: 1765

Answers (1)

Matthias Grün
Matthias Grün

Reputation: 1506

The problem is that you are declaring the parameter to be a non-const lvalue reference (as the error message suggests). An lvalue is essentially something that can be assigned to, so an lvalue reference is a reference to an existing object. SUN here, thus, is not an lvalue and therefore cannot be used to initialize the lvalue reference. A caller would have to call this method with an existing variable as its parameter if you declare it to be an lvalue reference. So remove the reference, since it's not necessary here if this is just supposed to be an input parameter.

See here for more information: http://en.cppreference.com/w/cpp/language/value_category

Upvotes: 4

Related Questions