Arnav Borborah Arnav Borborah - 3 months ago 9
C++ Question

Declaring enum at beginning of class vs end

Take the following 2 examples below:

struct Coord
{
private:
enum class Origin
{
Top_Left = 0,
Center
};
public:
Coord(Origin origin = Origin::Top_Left)
{}
};


int main()
{
}


Running this above, I get no errors. On the other hand, when I run this, I get the following error.

struct Coord
{
public:
Coord(Origin origin = Origin::Top_Left)
{}
private:
enum class Origin
{
Top_Left = 0,
Center
};
};


int main()
{
}



7:16: error: expected ')' before 'origin'


In addition, in Visual Studio 2015, I get the error for identifier
Origin
not being found in the constructor.

Why is this?

Error here: Live Example

Answer

In your second example you are using the enumeration before it is declared. You need to either declare it before first use (in the constructor) or add a forward declaration before first use (not going to fly here, but would in other scenarios).

The compiler needs to know what Origin and Origin::Top_Left is before its use in Coord(Origin origin = Origin::Top_Left). Remember; the compiler parses your code from the top down. It needs to know what types are before they are used. It does not view the entire compilation unit in a holistic fassion. The language just works like that - "must know what stuff is before stuff is used and I read from the top-down in every file". Sometimes "knowing stuff" needs to be the full definition, sometimes a forward declaration is enough (details of that are outside the scope of this question).

Comments