c++ - Include not required to define member function with enum? -


i forward declaring typed enum in header file. however, include not needed in cpp though defining member function it. referencing this stackoverflow article should not work. there no other includes indirectly including enum.

musicplayer.h - music::id being used declare member function legal

namespace music {    enum class id; }  class musicplayer { public:    load(music::id theme); }; 

musicplayer.cpp - music::id being used define member function without being included should illegal

void musicplayer::load(music::id theme) { }  

this new feature in c++11.
enums got rid of need integer #define constants, still had serious issues(like allowed compare other enum types, meaningless).
strongly typed enums (enum class) introduced in c++11. use of word class meant indicate each enum type different , not comparable other enum types. enum classes have advantages better scoping , feature forward declaration mentioned. not same class in link.

why useful??? forward declarations physical layout of code on disk different files or provide opaque objects part of api. in first case, care physical disk layout, using forward declaration allows declare enum type in header file while putting specific values cpp file. lets change list of possible enum values quite without forcing dependent files recompile. in second case, enum class can exposed type-safe otherwise opaque value returned 1 api function passed api function. code using api need not know possible values type can take on. since compiler still knows type, can enforce variables declared work type not confused variables working type.

refer here.

following example:

enum class mystronglytypedfloatenum,mystronglytypedcharenum;  void myfunction(mystronglytypedfloatenum f,mystronglytypedcharenum c);  enum class mystronglytypedfloatenum : float {....}  enum class mystronglytypedcharenum : char {....} 

this of course meaningless incomparable:

if(mystronglytypedfloatenum::f == mystronglytypedcharenum::c)  //not allowed 

another example:

#include <iostream> using namespace std; enum class fruit; void printfruit(fruit f); //allowed :d enum class fruit: int {mango = 1,apple = 2}; void printfruit(fruit f) {     if(f == fruit::mango) //f == 1 give error: no match ‘operator==’ (operand                             //types ‘fruit’ , ‘int’)         cout<<"fruit mango";     else         cout<<"fruit apple"; } int main() {     fruit myfruit=fruit::mango;     printfruit(myfruit);     return 0; } 

Comments

Popular posts from this blog

java - WrongTypeOfReturnValue exception thrown when unit testing using mockito -

php - Magento - Deleted Base url key -

android - How to disable Button if EditText is empty ? -