Reno
Reno

Reputation: 1139

How do I assign a value to an enum in constructor with a default value?

I have a class in C++ with a protected enum type and I am having trouble initialising that value in the constructor using a user defined argument, where it also has a default value.

Code:

class Student
{
protected:
  double gpa;
  enum gradeStatus {freshman, sophomore, junior, senior, blank};
public:
  Student(double inGPA = 0.0, gradeStatus inGrade = blank)
  :
  gpa(inGPA),
  gradeStatus(inGrade) //problem here
  {}
}; 

I am getting a compiler error due to the statement gradeStatus(inGrade):

Error (active) E0292 "gradeStatus" is not a nonstatic data member or base class of class "Student"

I want the emum to have a default value of blank if the Student object is created without supplying a gradeStatus value and if they do, then I want to initilize the Student object with the user supplied parameter.

Any help on how I can do that appreciated.

Upvotes: 1

Views: 118

Answers (2)

songyuanyao
songyuanyao

Reputation: 173034

gradeStatus is the name of enum type, but not a name of data member. The error message is trying to tell you that you should initialize a data member, but not a enum type.

You might want

class Student
{
protected:
  double gpa;
  enum gradeStatus {freshman, sophomore, junior, senior, blank}; // enum type definition
  gradeStatus status;                                            // data member definition
public:
  Student(double inGPA = 0.0, gradeStatus inGrade = blank)
  :
  gpa(inGPA),
  status(inGrade) // initialize the data member
  {}
}; 

Upvotes: 3

schteppe
schteppe

Reputation: 2084

gradeStatus(inGrade)

This line tries to assign inGrade to gradeStatus. “gradeStatus” is an enum type, and not a member of the class. To solve this, add a member to your class, for example:

gradeStatus status;

And then change the problematic line to:

status(inGrade)

Upvotes: 0

Related Questions