Sign in to follow this  

Initialization List Constants

This topic is 2840 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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.
Circle::Circle() : MIN_RADIUS(10.0), radius(MIN_RADIUS) {}

Share this post


Link to post
Share on other sites
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?

Share this post


Link to post
Share on other sites
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;

Share this post


Link to post
Share on other sites
If its a constant, just inline it in the class:

class Circle {

static const int MIN_RADIUS = 10;

int radius;

public:

Circle(): radius(MIN_RADIUS) {}

};



This only works with const integer types IIRC.

Share this post


Link to post
Share on other sites
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]

Share this post


Link to post
Share on other sites

This topic is 2840 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this