Jump to content
  • Advertisement
Sign in to follow this  
MasterDario

Creating a const variable in a class?

This topic is 4605 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

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 this post


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

Share this post


Link to post
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 this post


Link to post
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 this post


Link to post
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 this post


Link to post
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 this post


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

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!