• 14
• 12
• 9
• 10
• 13

# Creating a const variable in a class?

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

## Recommended Posts

Hey all, I created a circle class in c++ that basically outputs x and y coordinates, the Radius and the area of the circle. My question is i wanted to have a const variable like Pi = 3.14 in my class so that i can use that in my getArea function, so how can i define one in my class so that in the area function i can do return Pi*(Radius*Radius); instead of having to do return 3.14*(Radius*Radius);? Thank you, Dario

##### Share on other sites
Well you cant have literals in a class, so the best thing here is to have a const declared outside of the class, above it in the same header.

const float PI = 3.14159;

class sdgfsdf
{

...

The alternative is to create a static const float and then initialise it outside of the class, but i personally prefer the above method.

Dave

##### Share on other sites
awesome thanks, if i define that above int main(), would that be considered a global variable and work everywhere in my program?

##### Share on other sites
There are a couple of ways, some of them hacks or tricks that are not quite standard-compliant. The best way is to simply declare the member const, and initialize it via your constructor's initialization list:
class X{  public:    X(void) : PI(3.14f) { /* ... */ }  private:    const float PI;};

This is why initialization lists exist; to allow initialization of const and reference members. The downside to this is that you must remember to perform the initialization is all your constructors.

##### Share on other sites
No it wont work anywhere because the declaration only exists in hte main CPP file.

The best way is to put this definition into a header and include that wherever you need it.

Dave

##### Share on other sites
Unless you want to make circles with different values of p (e.g. non-Euclidean geometry), I suggest you make it a static constant.

##### Share on other sites
static const double PI = M_PI;

##### Share on other sites
Quote:
 Original post by Leadornstatic const double PI = M_PI;

Only static constant integral types maybe defined directly inside a class definition, for all other types they must be defined outside of a class definition.