# const or #define in classes

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

## Recommended Posts

I am using C++ and so far i have just used #define's for constant data. While it's not following the true spirit of C++, i have had no problem with it... until now. The issue is that i want to put it inside a class and use it as: SomeClass::CONST_VAR, instead of SOMECLASS_CONST_VAR. But can i initialise const data when it's declared in the class. i.e.
class SomeClass {
public:
static const int CONST_VAR = 20;
}


Or do i have to have separate definition & declaration?
// SomeClass.h
class SomeClass {
public:
static const int CONST_VAR = 20;
}

// SomeClass.cpp
int SomeClass::CONST_VAR = 20;  // Something like that (?)


Sorry if this is a rather dumb question but i though it would make more sense to me if someone explained it rather than me search for an answer on google.

##### Share on other sites
IIRC if it's an integral value you can define and declare in the same place (ie. in the class definition). Otherwise, you need to provide a single separate definition.

##### Share on other sites
Ah, i just found how to use "compile-time constants", i.e static const variables. It seems i can declare it like static const int CONST_VAR = 20;.
thanks anyway.

EDIT: ok, i see what you mean about "integral" values (i assume that means integer). The compiler says "only static const integral data members can be initialized within a class" when i try to use a float. That kinda sucks 'cos some of the constant data i use are floats.

##### Share on other sites
Quote:
 Original post by XTAL256EDIT: ok, i see what you mean about "integral" values (i assume that means integer). The compiler says "only static const integral data members can be initialized within a class" when i try to use a float. That kinda sucks 'cos some of the constant data i use are floats.

The usual solution to this is a function which returns the value:

class math {public:  static inline float pi() { return 3.141592f; }}

1. 1
2. 2
Rutin
16
3. 3
4. 4
5. 5

• 13
• 26
• 10
• 11
• 9
• ### Forum Statistics

• Total Topics
633735
• Total Posts
3013593
×