Link to home
Start Free TrialLog in
Avatar of CipherIS
CipherISFlag for United States of America

asked on

C++ Constants

I want to create a static class that will hold constants.  Then I want to create another class that can get the value of static class constants.

Can anyone provide a code sample?

Thx
SOLUTION
Avatar of Fabrice Lambert
Fabrice Lambert
Flag of France image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of pepr
pepr

I am not sure what is the real intention behind the question. You may be used to Java or C# where creating a static class for the purpose is necessary. In C++, you can create a "module" that contains only the constants. If you want to group them somehow, you can use namespace. If the situation is even simpler, you can define the constants in the form of a single header file with literals defined via the #define preprocesor macro.
Plus, I do not recommend making a class for the purpose of returning values from another one.

A class's purpose is to provide its own services, not the services of its neighbourg.
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
We're pretty much all ending at the same point:
A structure or enumeration (enclosed in a namespace or not, it is your choice).

@Sara:
Better use std::string instead of char* IMO.
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
>> just use a struct.
Yeah, that's what I said.
Sorry, Paul. I missed that.
Np. Actually thank you for reinforcing the idea and being more explicit with a piece of code.

I may actually get a chance to use C++11 in about a year. I thought I read that there is improvement in initializing static const float within a class. Is that right?
Better use std::string instead of char* IMO.
for a constant literal there is nothing as efficient than a  char or byte array. there is no advantage in using a std::string for code like i posted it, only overhead.

Sara
>>Better use std::string instead of char* IMO
I agree with Sara for the reasons she's stated. If you're dealing with const literal strings there's really no reason to consume the expense of using std::string, which will most likely cost a heap allocation and incurs the unnecessary cost of including the string header where it may very well not be needed. Use std::string when it makes sense to do so. Here it doesn't.