in following fragment of code receive compiler error when method data::setvalue(int, int) declared virtual:
struct data{ int ma; int mb; virtual void setvalues(int a, int b){ ma = a; mb = b; } }; struct threadmessage { enum type { data }; type msg_type; union content { data d; int a; }content; }; the error compiler (g++ (ubuntu/linaro 4.6.3-1ubuntu5) 4.6.3) gives me is:
struct.cpp:19:14: error: member 'data threadmessage::content::d' constructor not allowed in union
struct.cpp:19:14: error: member 'data threadmessage::content::d' copy assignment operator not allowed in union
this set of compiler errors took me off guard. in actual code, had many more attributes , functions. therefore, started looking put bloody operator=() , constructor didn't write them in struct data.
i know problem disappears when make data::setvalues not virtual. why struct data have constructor? when struct have constructor in c++? , why compilation error disappear when make virtual void data::setvalues(int, int) non virtual?
the error messages quoted misleading, no doubt wonder why making function non-virtual fixes problem.
first - structs , classes in c++ have constructors , copy assignment operators. if not create them yourself, created you. (you may delete default versions). in example there automatically generated constructor of data, , automatically generated assignment operator.
now why error messages misleading? because not true. in c++ can have union members constructors or assignment operators. problem starts when member functions not trivial. before c++11 not possible have union member non-trivial constructor. c++11 changed it, still without writing additional functions not possible use such union.
a struct/class virtual functions has non-trivial member functions constructor , assignment operator (because hidden data member needs managed). why when make function non-virtual errors disappear - member functions become trivial , struct may used union member without problems.
Comments
Post a Comment