Using static const + const as array bound - c++

I'm doing something like this
Class.hpp:
class Class {
private:
static const unsigned int arraySize;
int ar[arraySize+2];
};
Class.cpp:
#include <Class.hpp>
const unsigned int arraySize = 384;
The compiler (q++, a c++ compiler for the QNX OS based on g++) gives me error: array bound is not an integer constant while compiling a unit including Class.hpp (not while compiling Class.cpp).
Why isn't that working? I know that a static const member can be used as an array bound, guaranteed by the C++ standard (see this anwser). But why doesn't the compiler see the result of static const + const as a constant?

This is good code which should have been accepted by the compiler:
class Class {
const static int arraySize = 384;
int ar[arraySize+2];
};
and if it isn't, your compiler is broken.
However, if you move actual constant out of the header file to selected translation unit, that invalidates the code.
// Class.h
class Class {
const static int arraySize;
int ar[arraySize+2]; // ERROR
};
// Class.cpp
const int Class::arraySize = 384;
This is because the size of your Class object cannot be determined at compile time from the data available in the header alone. This is not exactly right reason, but reasoning along these lines helps to understand compilation errors such as this.
To avoid making such mistakes, you can replace static const int with an enum, e.g.
class Class {
enum { arraySize = 384 };
int ar[arraySize+2];
};

I'm surprised this actually compiles on gcc, as a comment says. Since the 384 isn't in the header file, the size of the Class is not known to other compilation units. It might not matter in some compilation units depending on how/if they are using Class, but I can't imagine this compiling:
// this is a source file called, say, blah.cpp
#include <Class.hpp>
void someFunc()
{
void *mem = malloc(sizeof(Class)); // size is not known, so this can't compile
// do something with mem
}
You need to have in your .hpp:
class Class {
private:
static const unsigned int arraySize = 384;
int ar[arraySize+2];
};
.. as it is in the OP that you link to here.

Related

c++ - expression did not evaluate to a constant - using constant from another class

[my code is quiet big, so I only pasted parts that seemed relevant to me, just tell me if you need to see more of it, thanks]
I defined a constant in a class (Animation) but now I split the class in two (AnimationsDefinition & AnimationsInstance), I can't use that constant from one class to the other
I included AnimationsDefinition.h before AnimationsInstance.h
common.h
#include "animationsDefinition.h"
#include "animationsInstance.h"
the compiler complains the constant cannot be evaluated
the below code used to be working, but now I use it in another class, it does not work anymore
the error I get :
error C2131: expression did not evaluate to a constant
note: failure was caused by non-constant arguments or reference to a non-constant symbol
note: see usage of 'EAST'
AnimationsDefinition.cpp
#include "common.h"
const int AnimationsDefinition::WEST = 0;
const int AnimationsDefinition::SOUTH = 1;
const int AnimationsDefinition::NORTH = 2;
const int AnimationsDefinition::EAST = 3;
...
AnimationsDefinition.h
#pragma once
class AnimationsDefinition
{
public:
static const int WEST;
static const int SOUTH;
static const int NORTH;
static const int EAST;
...
AnimationsInstance.cpp
#include "common.h"
void AnimationsInstance::update(float tpf)
{
switch (direction)
{
case AnimationsDefinition::EAST: <<<<<<<<< compilation error
{
...
Any help appreciated
regards
You can initialize the static const variables within the class itself.
class AnimationsDefinition
{
public:
static const int WEST = 0;
static const int SOUTH = 1;
static const int NORTH = 2;
static const int EAST = 3;
};
However, you would want to define them instead properly if you want to avoid ODR violations.
So use constexpr specifier which implies inline for static data members. And inline static data members can be defined in the class definition itself.
class AnimationsDefinition
{
public:
static constexpr int WEST = 0;
static constexpr int SOUTH = 1;
static constexpr int NORTH = 2;
static constexpr int EAST = 3;
};
As per [class.static.data]/3:
An inline static data member may be defined in the class definition and may specify a brace-or-equal-initializer.
Const variables can be used as constant expressions only after their initialiser has been encountered. In this case, that can be achieved by moving the initialisers into the header.
Note that moving the initialiser into the declaration within the class definition in the header does not make the declaration into a definition of the variable. The definitions must still remain in the source file, just without the initialisers.
Ok I found out I could define these in the class itself since they are static
You can define them in the class itself (or the header in general) only if you declare them inline.
However, it is more conventional to use (scoped) enumerations for switch cases.

private static data member + template class [duplicate]

What is the best way to initialize a private, static data member in C++? I tried this in my header file, but it gives me weird linker errors:
class foo
{
private:
static int i;
};
int foo::i = 0;
I'm guessing this is because I can't initialize a private member from outside the class. So what's the best way to do this?
The class declaration should be in the header file (Or in the source file if not shared).
File: foo.h
class foo
{
private:
static int i;
};
But the initialization should be in source file.
File: foo.cpp
int foo::i = 0;
If the initialization is in the header file then each file that includes the header file will have a definition of the static member. Thus during the link phase you will get linker errors as the code to initialize the variable will be defined in multiple source files.
The initialisation of the static int i must be done outside of any function.
Note: Matt Curtis: points out that C++ allows the simplification of the above if the static member variable is of const integer type (bool, char, char8_t [since C++20], char16_t, char32_t, wchar_t, short, int, long, long long, or any implementation-defined extended integer types, including any signed, unsigned, and cv-qualified variants.). You can then declare and initialize the member variable directly inside the class declaration in the header file:
class foo
{
private:
static int const i = 42;
};
For a variable:
foo.h:
class foo
{
private:
static int i;
};
foo.cpp:
int foo::i = 0;
This is because there can only be one instance of foo::i in your program. It's sort of the equivalent of extern int i in a header file and int i in a source file.
For a constant you can put the value straight in the class declaration:
class foo
{
private:
static int i;
const static int a = 42;
};
Since C++17, static members may be defined in the header with the inline keyword.
http://en.cppreference.com/w/cpp/language/static
"A static data member may be declared inline. An inline static data member can be defined in the class definition and may specify a default member initializer. It does not need an out-of-class definition:"
struct X
{
inline static int n = 1;
};
For future viewers of this question, I want to point out that you should avoid what monkey0506 is suggesting.
Header files are for declarations.
Header files get compiled once for every .cpp file that directly or indirectly #includes them, and code outside of any function is run at program initialization, before main().
By putting: foo::i = VALUE; into the header, foo:i will be assigned the value VALUE (whatever that is) for every .cpp file, and these assignments will happen in an indeterminate order (determined by the linker) before main() is run.
What if we #define VALUE to be a different number in one of our .cpp files? It will compile fine and we will have no way of knowing which one wins until we run the program.
Never put executed code into a header for the same reason that you never #include a .cpp file.
Include guards (which I agree you should always use) protect you from something different: the same header being indirectly #included multiple times while compiling a single .cpp file.
With a Microsoft compiler[1], static variables that are not int-like can also be defined in a header file, but outside of the class declaration, using the Microsoft specific __declspec(selectany).
class A
{
static B b;
}
__declspec(selectany) A::b;
Note that I'm not saying this is good, I just say it can be done.
[1] These days, more compilers than MSC support __declspec(selectany) - at least gcc and clang. Maybe even more.
int foo::i = 0;
Is the correct syntax for initializing the variable, but it must go in the source file (.cpp) rather than in the header.
Because it is a static variable the compiler needs to create only one copy of it. You have to have a line "int foo:i" some where in your code to tell the compiler where to put it otherwise you get a link error. If that is in a header you will get a copy in every file that includes the header, so get multiply defined symbol errors from the linker.
If you want to initialize some compound type (f.e. string) you can do something like that:
class SomeClass {
static std::list<string> _list;
public:
static const std::list<string>& getList() {
struct Initializer {
Initializer() {
// Here you may want to put mutex
_list.push_back("FIRST");
_list.push_back("SECOND");
....
}
}
static Initializer ListInitializationGuard;
return _list;
}
};
As the ListInitializationGuard is a static variable inside SomeClass::getList() method it will be constructed only once, which means that constructor is called once. This will initialize _list variable to value you need. Any subsequent call to getList will simply return already initialized _list object.
Of course you have to access _list object always by calling getList() method.
C++11 static constructor pattern that works for multiple objects
One idiom was proposed at: https://stackoverflow.com/a/27088552/895245 but here goes a cleaner version that does not require creating a new method per member.
main.cpp
#include <cassert>
#include <vector>
// Normally on the .hpp file.
class MyClass {
public:
static std::vector<int> v, v2;
static struct StaticConstructor {
StaticConstructor() {
v.push_back(1);
v.push_back(2);
v2.push_back(3);
v2.push_back(4);
}
} _staticConstructor;
};
// Normally on the .cpp file.
std::vector<int> MyClass::v;
std::vector<int> MyClass::v2;
// Must come after every static member.
MyClass::StaticConstructor MyClass::_staticConstructor;
int main() {
assert(MyClass::v[0] == 1);
assert(MyClass::v[1] == 2);
assert(MyClass::v2[0] == 3);
assert(MyClass::v2[1] == 4);
}
GitHub upstream.
Compile and run:
g++ -ggdb3 -O0 -std=c++11 -Wall -Wextra -pedantic -o main.out main.cpp
./main.out
See also: static constructors in C++? I need to initialize private static objects
Tested on Ubuntu 19.04.
C++17 inline variable
Mentioned at: https://stackoverflow.com/a/45062055/895245 but here is a multifile runnable example to make it even clearer: How do inline variables work?
This awesome C++17 feature allow us to:
conveniently use just a single memory address for each constant
store it as a constexpr: How to declare constexpr extern?
do it in a single line from one header
main.cpp
#include <cassert>
#include "notmain.hpp"
int main() {
// Both files see the same memory address.
assert(&notmain_i == notmain_func());
assert(notmain_i == 42);
}
notmain.hpp
#ifndef NOTMAIN_HPP
#define NOTMAIN_HPP
inline constexpr int notmain_i = 42;
const int* notmain_func();
#endif
notmain.cpp
#include "notmain.hpp"
const int* notmain_func() {
return &notmain_i;
}
Compile and run:
g++ -c -o notmain.o -std=c++17 -Wall -Wextra -pedantic notmain.cpp
g++ -c -o main.o -std=c++17 -Wall -Wextra -pedantic main.cpp
g++ -o main -std=c++17 -Wall -Wextra -pedantic main.o notmain.o
./main
GitHub upstream.
I don't have enough rep here to add this as a comment, but IMO it's good style to write your headers with #include guards anyway, which as noted by Paranaix a few hours ago would prevent a multiple-definition error. Unless you're already using a separate CPP file, it's not necessary to use one just to initialize static non-integral members.
#ifndef FOO_H
#define FOO_H
#include "bar.h"
class foo
{
private:
static bar i;
};
bar foo::i = VALUE;
#endif
I see no need to use a separate CPP file for this. Sure, you can, but there's no technical reason why you should have to.
You can also include the assignment in the header file if you use header guards. I have used this technique for a C++ library I have created. Another way to achieve the same result is to use static methods. For example...
class Foo
{
public:
int GetMyStatic() const
{
return *MyStatic();
}
private:
static int* MyStatic()
{
static int mStatic = 0;
return &mStatic;
}
}
The above code has the "bonus" of not requiring a CPP/source file. Again, a method I use for my C++ libraries.
The linker problem you encountered is probably caused by:
Providing both class and static member definition in header file,
Including this header in two or more source files.
This is a common problem for those who starts with C++. Static class member must be initialized in single translation unit i.e. in single source file.
Unfortunately, the static class member must be initialized outside of the class body. This complicates writing header-only code, and, therefore, I am using quite different approach. You can provide your static object through static or non-static class function for example:
class Foo
{
// int& getObjectInstance() const {
static int& getObjectInstance() {
static int object;
return object;
}
void func() {
int &object = getValueInstance();
object += 5;
}
};
I follow the idea from Karl. I like it and now I use it as well.
I've changed a little bit the notation and add some functionality
#include <stdio.h>
class Foo
{
public:
int GetMyStaticValue () const { return MyStatic(); }
int & GetMyStaticVar () { return MyStatic(); }
static bool isMyStatic (int & num) { return & num == & MyStatic(); }
private:
static int & MyStatic ()
{
static int mStatic = 7;
return mStatic;
}
};
int main (int, char **)
{
Foo obj;
printf ("mystatic value %d\n", obj.GetMyStaticValue());
obj.GetMyStaticVar () = 3;
printf ("mystatic value %d\n", obj.GetMyStaticValue());
int valMyS = obj.GetMyStaticVar ();
int & iPtr1 = obj.GetMyStaticVar ();
int & iPtr2 = valMyS;
printf ("is my static %d %d\n", Foo::isMyStatic(iPtr1), Foo::isMyStatic(iPtr2));
}
this outputs
mystatic value 7
mystatic value 3
is my static 1 0
Also working in privateStatic.cpp file :
#include <iostream>
using namespace std;
class A
{
private:
static int v;
};
int A::v = 10; // possible initializing
int main()
{
A a;
//cout << A::v << endl; // no access because of private scope
return 0;
}
// g++ privateStatic.cpp -o privateStatic && ./privateStatic
What about a set_default() method?
class foo
{
public:
static void set_default(int);
private:
static int i;
};
void foo::set_default(int x) {
i = x;
}
We would only have to use the set_default(int x) method and our static variable would be initialized.
This would not be in disagreement with the rest of the comments, actually it follows the same principle of initializing the variable in a global scope, but by using this method we make it explicit (and easy to see-understand) instead of having the definition of the variable hanging there.
One "old-school" way to define constants is to replace them by a enum:
class foo
{
private:
enum {i = 0}; // default type = int
enum: int64_t {HUGE = 1000000000000}; // may specify another type
};
This way doesn't require providing a definition, and avoids making the constant lvalue, which can save you some headaches, e.g. when you accidentally ODR-use it.
Here are all possibilities and errors in one simple example ...
#ifndef Foo_h
#define Foo_h
class Foo
{
static const int a = 42; // OK
static const int b {7}; // OK
//static int x = 42; // ISO C++ forbids in-class initialization of non-const static member 'Foo::x'
//static int y {7}; // ISO C++ forbids in-class initialization of non-const static member 'Foo::x'
static int x;
static int y;
int m = 42;
int n {7};
};
// Foo::x = 42; // error: 'int Foo::x' is private
int Foo::x = 42; // OK in Foo.h if included in only one *.cpp -> *.o file!
int Foo::y {7}; // OK
// int Foo::y {7}; // error: redefinition of 'int Foo::y'
// ONLY if the compiler can see both declarations at the same time it,
// OTHERWISE you get a linker error
#endif // Foo_h
But better place this in Foo.cpp. This way you can separately compile each file and link them later, otherwise Foo:x will be present in multiple object files and cause a linker error. ...
// Foo::x = 42; // error: 'int Foo::x' is private, bad if Foo::X is public!
int Foo::x = 42; // OK in Foo.h if included in only one *.cpp -> *.o file!
int Foo::y {7}; // OK
Does this serves your purpose?
//header file
struct MyStruct {
public:
const std::unordered_map<std::string, uint32_t> str_to_int{
{ "a", 1 },
{ "b", 2 },
...
{ "z", 26 }
};
const std::unordered_map<int , std::string> int_to_str{
{ 1, "a" },
{ 2, "b" },
...
{ 26, "z" }
};
std::string some_string = "justanotherstring";
uint32_t some_int = 42;
static MyStruct & Singleton() {
static MyStruct instance;
return instance;
}
private:
MyStruct() {};
};
//Usage in cpp file
int main(){
std::cout<<MyStruct::Singleton().some_string<<std::endl;
std::cout<<MyStruct::Singleton().some_int<<std::endl;
return 0;
}
I just wanted to mention something a little strange to me when I first encountered this.
I needed to initialize a private static data member in a template class.
in the .h or .hpp, it looks something like this to initialize a static data member of a template class:
template<typename T>
Type ClassName<T>::dataMemberName = initialValue;

c++ static class variable without cpp file

I have a simple class for storing sensor data which can be summarized as
class Data
{
public:
Data(){timestamp = Time::now(); id = sNextID++; data = 0; type = DATA_TYPE_UNKNOWN;}
double data;
Time timestamp;
DataType type;
private:
static unsigned int sNextID;
};
I have a header file that declares a bunch of similar data classes. Given the simplicity of the classes there is no need for an implementation cpp file.
The problem is, without an implementation file how do I initialize sNextID? I read somewhere that it defaults to 0 which would be fine, although relying on that seems a bit hackish. More importantly, though, without initializing it somewhere the linker complains of an undefined reference.
Use inline function (free-standing or member):
inline unsigned &sNextID()
{
static unsigned data = 0;
return data;
}
Or class template (defenition of it's statics can be in header file):
template<typename tag>
struct Foo
{
static unsigned sNextID;
};
template<typename tag>
unsigned Foo<tag>::sNextID=0;
Update: In C++17 inline variables are available:
struct Foo
{
static inline unsigned sNextID;
};
in the header file (let's say it's name is data.h), add this at the end
class Data
{
.....
private:
static unsigned int sNextID;
};
#ifdef MY_INIT
unsigned int sNextID = 0;
#endif
in the file where you have main
#define MY_INIT
#include "data.h"
in all other files where you are including the header, just a plain
#include "data.h"
This will ensure that the line unsigned int sNextID = 0; will be compiled into only one translation unit - the one with main.

Arranging template related code in different headers

The code below works as long as I keep it all in the "main.cpp" file.
//#include "Travel.h"
//#include "Obj.h"
// "Travel.h"
typedef int travel_t;
class Travel
{
public:
static const travel_t AIR;
static const travel_t WATER;
static const travel_t LAND;
};
// "Travel.cpp"
// #ifndef TRAVEL_H
// #define TRAVEL_H
//
// #include "Travel.h"
const travel_t Travel::AIR = -2;
const travel_t Travel::WATER = -1;
const travel_t Travel::LAND = 0;
// #endif //TRAVEL_H
// "Obj.h"
// #ifndef OBJ_H
// #define OBJ_H
//
//#include "Travel.h"
template<typename T, travel_t travel>
class Obj
{
public:
void foo(){};
};
// #endif //OBJ_H
// "main.cpp"
int main()
{
Obj<int, Travel::AIR> objAirTravel;
objAirTravel.foo();
return 0;
}
However, as soon as I moved code to different headers and implementation files as indicated, it doesn't compile any more. :-( How can I fix that problem? What is the problem/rule behind it? This is the compiler error I get (using gcc):
main.cpp|45|error: 'Travel::AIR' is not a valid template argument for type 'int' because it is a non-constant expression|
main.cpp|45|error: invalid type in declaration before ';' token|
main.cpp|47|error: request for member 'foo' in 'objAirTravel', which is of non-class type 'int'|
In order to use a constant as a template argument, its value must be available in the current translation unit. When you move the definition of Travel::Air to a different source file, its value is no longer available to the compiler in main.
Since it's an integer constant, you can declare the value in the declaration inside the class:
class Travel
{
public:
static const travel_t AIR = -2;
static const travel_t WATER = -1;
static const travel_t LAND = 0;
};
Now the values are available to use as template arguments in any translation unit that includes this class definition.

Initializing Constant Static Array In Header File

I have just found out that the following is not valid.
//Header File
class test
{
const static char array[] = { '1', '2', '3' };
};
Where is the best place to initialize this?
The best place would be in a source file
// Header file
class test
{
const static char array[];
};
// Source file
const char test::array[] = {'1','2','3'};
You can initialize integer types in the class declaration like you tried to do; all other types have to be initialized outside the class declaration, and only once.
You can always do the following:
class test {
static const char array(int index) {
static const char a[] = {'1','2','3'};
return a[index];
}
};
A couple nice things about this paradigm:
No need for a cpp file
You can do range checking if you want to
You avoid having to worry about the static initialization fiasco
//Header File
class test
{
const static char array[];
};
// .cpp
const char test::array[] = { '1', '2', '3' };
Now, in C++17, you can use inline variable
How do inline variables work?
A simple static data member(N4424):
struct WithStaticDataMember {
// This is a definition, no out­of­line definition is required.
static inline constexpr const char *kFoo = "foo bar";
};
In your example:
//Header File
class test
{
inline constexpr static char array[] = { '1', '2', '3' };
};
should just work
With constexpr you must define the value on the header even in C++11
If you use constexpr instead of const, then this answer suggests that you not only can, but must, define on header even in C++11:
#include <cassert>
struct MyClass {
static constexpr int is[] = {1, 2, 3};
static constexpr int i = 1;
};
// TODO is this ever mandatory? Create example that fails on -std=c++11.
// Pretty sure never mandatory in C++17 https://stackoverflow.com/a/40959093/895245
// constexpr int MyClass::is[];
int main (void) {
assert(MyClass::is[0] == 1);
assert(&MyClass::is[0] == &MyClass::is[1] - 1);
assert(MyClass::i == 1);
assert(&MyClass::i == &MyClass::i);
}
Compile and run with:
g++-10 -ggdb3 -O0 -std=c++11 -Wall -Wextra -pedantic -o main.out main.cpp
./main.out
If instead you try:
struct MyClass {
static constexpr int is[];
};
constexpr int MyClass::is[] = {1, 2, 3};
compilation fails with:
main.cpp:4:26: error: ‘constexpr’ static data member ‘is’ must have an initializer
Tested on Ubuntu 20.04.
This is kind of an abuse of the system, but if you REALLY want to define it in the header file (and you don't have C++17), you can do this. It won't be a static member, but it will be a constant that only takes up storage per compilation unit (rather than per class instance):
(Put all of this code in the header file.)
namespace {
const char test_init_array[] = {'1', '2', '3'};
}
class test {
public:
const char * const array;
test() : array(test_init_array) {}
};