M.T
M.T

Reputation: 303

How to set the default value of enum type variable?

How to set the default value of the enum type tip, I tried setting it to 0 or 1, or nothing, but I get the same error?

enum tip {
pop,
rap,
rock
};

class Pesna{
private:
char *ime;
int vremetraenje;
tip tip1;

public:
//constructor
Pesna(char *i = "NULL", int min = 0, tip t){
    ime = new char[strlen(i) + 1];
    strcpy(ime, i);
    vremetraenje = min;
    tip1 = t;
}

};

Upvotes: 2

Views: 4943

Answers (2)

7107enthusiast
7107enthusiast

Reputation: 11

Don’t think of enums as numbers like 0 or 1 (in some cases they can even be signed or unsigned). Think of them like more like a class/struct in the way that you refer to them. So using

tip = 1

wouldn’t make since because ‘tip’ isn’t a number, it’s its own entity. Without explicitly stating enums start somewhere else like

enum tip { pop = 7, ...}

the first enum will start at 0. So you can cast/uncast using those representations with ‘numbers’, but again I would be careful with that. Also in general, it’s nicer to declare class-specific enums inside the class’s public namespace like

class Pesna {
  public:
    enum tip { pop, ...}

and then use the scope resolution operator to access them

Pesna::tip

Upvotes: 1

πάντα ῥεῖ
πάντα ῥεῖ

Reputation: 1

You must set it to one of the enum values, like:

Pesna(char *i = "NULL", int min = 0, tip t = pop)
                                        // ^^^^^

Another techique is to use a Default value declared in the enum itself and use that one. This makes it easier if you change your mind later what the default should be:

enum tip {
    pop,
    rap,
    rock,
    Default = rap, // Take care not to use default, that's a keyword
};

Pesna(char *i = "NULL", int min = 0, tip t = Default)
                                        // ^^^^^^^^^

Upvotes: 5

Related Questions