Creating a const variable in a class?

Started by
6 comments, last by snk_kid 17 years, 11 months ago
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
n/a
Advertisement
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
awesome thanks, if i define that above int main(), would that be considered a global variable and work everywhere in my program?
n/a
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.
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
Unless you want to make circles with different values of p (e.g. non-Euclidean geometry), I suggest you make it a static constant.
static const double PI = M_PI;
Quote:Original post by Leadorn
static 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.

This topic is closed to new replies.

Advertisement