I have like 5 classes, 3 of then need around 15 constants the other 2 classes need only 2 of the 15.

I was thinking of having a header file to contain all the constants in header file and just include them in the header files of all 5 classes.

My concern is for the 2 classes that only uses the 2 of the 15 constants... is there some space wasted since all 15 are declared or some performance problems of doing this? Or does the preprocessor get's only constants that are used in that classes?

A const in C++ replaces the #define in C.

#include <iostream>

int main ( ) {
    const int magic = 42;
    int *breaker = (int*)&magic;
    std::cout << magic << " " << *breaker << std::endl;
    ++(*breaker);   /* there goes all the const correctness */
    std::cout << magic << " " << *breaker << std::endl;
    return 0;
}

$ g++ foo.cpp
$ ./a.exe
42 42
42 43

Because the compiler 'knows' the value is a constant, there is no need to reference the store, but instead the known value is substituted inline. So what you get in effect is std::cout << 42 << " " << *breaker << std::endl; Unless you do things like create pointers to your consts, the compiler would not store them as separate named objects in memory. So you can create them as you need them and not have to worry that you're creating a lot of dead space in the executable.

if they are const integral values known at compile time, and you define them as

enum { const_one = 567, const_two = -34, /* ... */ };

no storage would be allocated at all.

if the values are not known at compile time, and you declare them as

extern const int const_one ;
extern const int const_two ;
// etc

storage would be allocated once for each variable (there would be only one definition).

if they are const integral values known at compile time, and you define them as

const int const_one = 567 ;
const int const_two = -34 ;
// etc

these are constants known at compile time; the optimizer would optimize away allocation of any storage for these unless you take a pointer or reference to it eg.

const int* ptr = &const_one ;

one may be more concerned about the pollution of the global namespace by these 15 identifiers; in any case a good c++ program should have only main outside of any namespace.

This article has been dead for over six months. Start a new discussion instead.