-1

I know I can initialize int variables in a constructor with a member initialization list, but can I initialize an enum type in an member initialization list like in the example below?

enum number{zero, one, two, three};

class Example{
    int test;
    number number_enum;
public:
    Example(int test_arg, number number_enum_arg): test(test_arg), 
number_enum(number_enum_arg){

    }  

};

Also, I know it is better to initialize variables using an member initialization list, rather than using the assignment operator, but exactly is that?

ptushev
  • 177
  • 3
  • 16
  • 4
    Did you get an error when you tried this? – NathanOliver Apr 25 '19 at 18:24
  • 1
    For your follow up question, see: https://stackoverflow.com/questions/926752/why-should-i-prefer-to-use-member-initialization-list – NathanOliver Apr 25 '19 at 18:25
  • What happened when you tried this code? – SergeyA Apr 25 '19 at 18:27
  • Will you create a separate question for each type? Like I can initialize `int`, can I initialize `short`? Then can I initialize `double` etc. Do you really think that member initialization only defined for type `int`? – Slava Apr 25 '19 at 18:27
  • @NathanOliver I didn't get an errror but when I tried this in a program i wasn't sure whether it passed the value – ptushev Apr 25 '19 at 18:32

1 Answers1

2

The code in your example will work, you can initialize enums and virtually all types in an initializer list. Add a line to your constructor to print it out, you'll see.

B.McCready
  • 61
  • 4