Circle::Circle() : MIN_RADIUS(10.0), radius(MIN_RADIUS) {}
Initialization List Constants
Good evening. I would like to initialize a constant in a constructor's initialization list but, I would also like to assign it's value to a variable. Can this be done? Example below in C++ and thanks for looking.
You can do it but remember that members are initialized in the order they are declared in the class, not in the order they appear in the initialization list (make sure MIN_RADIUS is declared before radius).
P.S Wouldn't it be better to reserve ALL_CAPS for macros?
P.S Wouldn't it be better to reserve ALL_CAPS for macros?
It sounds like MIN_RADIUS is a constant that applies to all instances of Circle. In that case, you should make it static, and initialize it separately:
class Circle { static int MIN_RADIUS; int radius; public: Circle(): radius(MIN_RADIUS) {}};// This part goes in a .cpp file, not a header.int Circle::MIN_RADIUS = 10;
If its a constant, just inline it in the class:
This only works with const integer types IIRC.
class Circle { static const int MIN_RADIUS = 10; int radius;public: Circle(): radius(MIN_RADIUS) {}};
This only works with const integer types IIRC.
Quote:You can do it but remember that members are initialized in the order they are declared in the class, not in the order they appear in the initialization list (make sure MIN_RADIUS is declared before radius).
Sidenote: gcc will warn you if the ordering is not the same.
Quote:It sounds like MIN_RADIUS is a constant that applies to all instances of Circle. In that case, you should make it static, and initialize it separately:
Though in some cases it is indeed useful (posting this because OP did not specify exactly what he wants to achieve), like e.g.:
class Token {public: enum Type { add, sub, mul, div }; Token (Type type) : type(type) {}private: const Type type;};
edit: forgot to const the type
[Edited by - phresnel on March 6, 2010 2:15:20 AM]
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement