c++ class member of same type - c++

I have the following situation:
class Foo
{
public:
static const Foo memberOfFoo;
........
}
So the thing is I can't initialize it in the same line where I declared it, and, I can't initialize it via Initializations List in the constructor, does anyone know what to do?

Put this outside of the class definition then:
const Foo Foo::memberOfFoo = whateverValue;
That is the definition of Foo::memberOfFoo, which can supply an initializer and has to go into the .cpp file (like any other definition of objects, it can only appear once in the whole program, otherwise you will get linker errors).
Sometimes you will find code that doesn't have definitions for its static data members:
struct A {
// sometimes, code won't have an "const int A::x;" anywhere!
static const int x = 42;
};
Omitting the definition like that is valid only if A::x is never address-taken and never passed to reference parameters. A more formal way to say when it is valid to omit the definition is: "When all uses of A::x immediately read the stored value of A::x". That's the case for many static integer constants.

Class statics other than constant integral types need to/can be initialized at the point of definition. You need to declare your (not so)memberOfFoo somewhere, by adding
const Foo Foo::memberOfFoo = /*construct here*/;

This is how you can implement initialization...
class Foo
{
public:
static const Foo memberOfFoo;
Foo(int, double)
{
...
};
};
const Foo Foo::memberOfFoo(42, 3.141592654);
...

Related

c++ initialisation order of static members

Just wondering if in the following the static members are initialised before the Foo class object is initialised. Since both are static variables, one a static member and the other a static global variable, initialisation order is not guaranteed or specified.
struct Foo
{
Foo() { assert(a == 7); }
static inline int a = 7;
};
Foo foo;
int main()
{
}
So the initialisation order between the global Foo and the static class member is not defined, you would think there is no guarantee. However, I'm thinking that before a Foo is instantiated that the Foo class would need to be completed/initialised first, and so in that case that there might be a guarantee that the static member variable would be initialised first.
I'm thinking that before a Foo is instantiated that the Foo class would need to be completed/initialised first
That is not generally the case, so you should be careful with that assumption.
However, in your specific example, the order of initialization is guaranteed. The initializer of a is a constant expression and therefore a will be constant-initialized. Constant-initialization is guaranteed to happen before any dynamic initialization, which the initialization of foo is.
Even if a was not constant-initialized, there wouldn't be an issue here, because foo is defined after a in the same translation unit, foo is not an inline or template variable and because Foo is not a template. If either of these requirements were not fulfilled, there could be problems in the ordering guarantees.

"warning C4172: returning address of local variable or temporary" when returning reference to static member

I have this class with a function that returns a value. For complicated reasons, the value needs to be returned as a const reference.
(minimal working example contains an int array, real code has more complex objects, hence the reference)
class Foo
{
public:
static constexpr const int OUT_OF_BOUNDS_VALUE = -9999;
const int& ret(int i) const { return i < 0 || i > 4 ? OUT_OF_BOUNDS_VALUE : test[i]; }
private:
int test[5] = {0, 1, 2, 3, 4};
};
This gives me warning C4172: returning address of local variable or temporary in VS2015 and it doesn't even compile with GCC.
Adding the line constexpr const int Foo::OUT_OF_BOUNDS; outside of Foo lets GCC compile just fine. VS2015 still gives the warning.
Removing constexpr and splitting the declaration from the definition fixes the warning, but why should I have to do that?
OUT_OF_BOUNDS isn't local, and it isn't temporary, right? Does it not have an address when it is defined and declared inside of the class definition?
See the warning live: https://godbolt.org/z/fv397b9rr
The problem is that in C++11, we have to add a corresponding definition for a static constexpr declaration of a class' data member. This is explained in more detail below:
C++11
class Foo
{
public:
static constexpr const int OUT_OF_BOUNDS_VALUE = -9999; //THIS IS A DECLARATION IN C++11 and C++14
//other members here
};
In the above code snippet(which is for C++11,C++14), we have a declaration of the static data member OUT_OF_BOUNDS_VALUE inside the class. And so, in exactly one translation unit we have to provide a corresponding definition. Otherwise you'll get a linker error which can be seen here.
That is, in exactly one translation unit we should write:
constexpr const int Foo::OUT_OF_BOUNDS;//note no initializer
C++17
class Foo
{
public:
static constexpr const int OUT_OF_BOUNDS_VALUE = -9999; //THIS IS A DEFINITION IN C++17
//other members here
};
In the above code snippet(which is for C++17) we have a definition of the static data member OUT_OF_BOUNDS_VALUE inside the class. So since C++17, we don't have to provide the definition of OUT_OF_BOUNDS_VALUE anywhere else since we already have a definition for it inside the class.
The warning that you're getting with MSVC seems to be a bug.
What happens when you use the constexpr in your function is that a temporary local instance is created. You could try to leave out constexpr and static in the declaration of your static member OUT_OF_BOUNDS so you have a const object / instance you can get a reference of.
EDIT:
If you must have a static member, declare it const static int and put in the definition const int Foo::OUT_OF_BOUNDS = -1; in an appropriate place.
test[i] is an int, you're binding it to a reference to const int in the return statement. No?

c++ : why I can't assign a value to a non-const static member "inside" a class?

I'm new to C++, and I just can't understand that why I can't assign a value to a non-const static member inside a class (like we do in java static int x = 12; ) even thought I can
declare a non-const static member (static int x;)
declare a static const member (static const x;)
assign a static const member (static const int x = 12;)
note: my class and my main() function are in the same file
In general
A static variable inside a class, just like everything else, is just a declaration by default. C++ then requires you to provide a single definition per entity that requires one, that's the One Definition Rule. The definition is where the initializer (which is not an assignment, but a construction) goes, since there should be only one as well. It is typically placed in a .cpp file so that it can't be accidentally duplicated by #includes.
The constant case
When a static member is a constant integer or enumeration, and is initialized with a compile-time expression, the initializer is allowed to be placed on the declaration, and the definition skipped. This is a result of a combination of old rules and isn't really interesting today IMO.
Proper inline initialization
Since C++17 introduced inline variables, you can use them as static members. The rules are roughly the same as inline functions, and are pretty sensible: you can provide multiple definition of an inline entity, you are responsible for ensuring that they are all strictly identical, and the implementation is responsible for collapsing them into a single definition with its initializer. Thus, what you're looking for is written:
struct Foo {
static inline int bar = 42;
// ^^^^^^
};
You have to initialise the static member outside the class definition like in this example:
class Box {
public:
static int x;
};
// Initialize static member of class Box outside the class definition
int Box::x = 12;
int main(void) {
...
}

static constant members for array size

MyClass.h
class MyClass
{
public:
static const int cTotalCars;
private:
int m_Cars[cTotalCars];
};
MyClass.cpp
#include "MyClass.h"
const int MyClass::cTotalCars = 5;
The above code doesn't work because it will say "expected constant expression" for the m_Cars array.
class MyClass
{
public:
static const int cTotalCars = 5;
private:
int m_Cars[cTotalCars];
};
The above will work, but I am told that I should always define static members in the CPP file, outside the class definition. What can I do?
Static const members of simple type are a exception to that rule, so you latter code is correct.
This exception is a fairly modern one (from C++98, but not implemented by every compiler until a few years later) so many old-fashioned teachers are not yet aware of it. They prefer the idiom:
class MyClass
{
public:
enum { cTotalCars = 5 };
private:
int m_Cars[cTotalCars];
};
That behaves exactly the same, but makes little sense nowadays.
The above will work, but I am told that I should always define static members in the CPP file, outside the class definition. What can I do?
Well, what you have been suggested to do: define the static members in the CPP. Note that in the code above the static member is not defined even if the value is stated. The proper final code would look like:
// .h (ignoring all but the static member)
class MyClass {
static const int cTotalCars = 5; // declaration and initialization
};
// .cpp
static const int MyClass::cTotalCars; // definition (cannot have value!)
The definition in the .cpp file is what actually reserves the space for the variable when used as an lvalue. For a simple test that verifies that without that line the variable is not defined you can do:
void f( const int & x ) {}
int main() {
f( MyClass::cTotalCars );
}
Without the line in the .cpp file the code above will trigger a linker error pointing to the missing definition of MyClass::cTotalCars. The problem with the code is that it uses the static const member (by the definition of use in the standard), and that requires the member to be defined. While the case of using the constant to define the array size does not constitute use.
I would rather use a #define C_TOTAL_CARS 5, then static const int cTotalCars = C_TOTAL_CARS; and then also, int m_Cars[C_TOTAL_CARS];.
If is was a static int you would need to place it into the .cpp file. You do not need the keyword static in this instance as all you want is a constant. Just use const int cTotalCars = 5;. It is better than #define as you have type info and also it has a symbol that can be viewed in a debugger.
It just can't works if you define size of the array is set in cpp file. All class clients should know the size of class instance but they just have no idea about .cpp file because you only put #include "MyClass.h" in client-files.
In other words - your class definition is varies depending on the cpp-file which is not used while compile files that uses MyClass.

Initialize static variables in C++ class?

I have noticed that some of my functions in a class are actually not accessing the object, so I made them static. Then the compiler told me that all variables they access must also be static – well, quite understandable so far. I have a bunch of string variables such as
string RE_ANY = "([^\\n]*)";
string RE_ANY_RELUCTANT = "([^\\n]*?)";
and so on in the class. I have then made them all static const because they never change. However, my program only compiles if I move them out of the class: Otherwise, MSVC++2010 complains "Only static constant integral variables may be initialized within a class".
Well that's unfortunate. Is there a workaround? I would like to leave them inside the class they belong to.
They can't be initialised inside the class, but they can be initialised outside the class, in a source file:
// inside the class
class Thing {
static string RE_ANY;
static string RE_ANY_RELUCTANT;
};
// in the source file
string Thing::RE_ANY = "([^\\n]*)";
string Thing::RE_ANY_RELUCTANT = "([^\\n]*?)";
Update
I've just noticed the first line of your question - you don't want to make those functions static, you want to make them const. Making them static means that they are no longer associated with an object (so they can't access any non-static members), and making the data static means it will be shared with all objects of this type. This may well not be what you want. Making them const simply means that they can't modify any members, but can still access them.
Mike Seymour has given you the right answer, but to add...
C++ lets you declare and define in your class body only static const integral types, as the compiler tells. So you can actually do:
class Foo
{
static const int someInt = 1;
static const short someShort = 2;
// etc.
};
And you can't do that with any other type, in that cases you should define them in your .cpp file.
Some answers including even the accepted answer seem to be a little misleading.
You don't have to
Always assign a value to static objects when initializing because that's optional.
Create another .cpp file for initializing since it can be done in the same header file.
You can even initialize a static object in the same class scope just like a normal variable using the inline keyword.
Initialize with no values in the same file
#include <string>
class A
{
static std::string str;
static int x;
};
std::string A::str;
int A::x;
Initialize with values in the same file
#include <string>
class A
{
static std::string str;
static int x;
};
std::string A::str = "SO!";
int A::x = 900;
Initialize in the same class scope using the inline keyword
#include <string>
class A
{
static inline std::string str = "SO!";
static inline int x = 900;
};
Since C++11 it can be done inside a class with constexpr.
class stat {
public:
// init inside class
static constexpr double inlineStaticVar = 22;
};
The variable can now be accessed with:
stat::inlineStaticVar
Static member variables must be declared in the class and then defined outside of it!
There's no workaround, just put their actual definition in a source file.
From your description it smells like you're not using static variables the right way. If they never change you should use constant variable instead, but your description is too generic to say something more.
Static member variables always hold the same value for any instance of your class: if you change a static variable of one object, it will change also for all the other objects (and in fact you can also access them without an instance of the class - ie: an object).
I feel it is worth adding that a static variable is not the same as a constant variable.
using a constant variable in a class
struct Foo{
const int a;
Foo(int b) : a(b){}
}
and we would declare it like like so
fooA = new Foo(5);
fooB = new Foo(10);
// fooA.a = 5;
// fooB.a = 10;
For a static variable
struct Bar{
static int a;
Foo(int b){
a = b;
}
}
Bar::a = 0; // set value for a
which is used like so
barA = new Bar(5);
barB = new Bar(10);
// barA.a = 10;
// barB.a = 10;
// Bar::a = 10;
You see what happens here. The constant variable, which is instanced along with each instance of Foo, as Foo is instanced has a separate value for each instance of Foo, and it can't be changed by Foo at all.
Where as with Bar, their is only one value for Bar::a no matter how many instances of Bar are made. They all share this value, you can also access it with their being any instances of Bar. The static variable also abides rules for public/private, so you could make it that only instances of Bar can read the value of Bar::a;
Just to add on top of the other answers. In order to initialize a complex static member, you can do it as follows:
Declare your static member as usual.
// myClass.h
class myClass
{
static complexClass s_complex;
//...
};
Make a small function to initialize your class if it's not trivial to do so. This will be called just the one time the static member is initialized. (Note that the copy constructor of complexClass will be used, so it should be well defined).
//class.cpp
#include myClass.h
complexClass initFunction()
{
complexClass c;
c.add(...);
c.compute(...);
c.sort(...);
// Etc.
return c;
}
complexClass myClass::s_complex = initFunction();
If your goal is to initialize the static variable in your header file (instead of a *.cpp file, which you may want if you are sticking to a "header only" idiom), then you can work around the initialization problem by using a template. Templated static variables can be initialized in a header, without causing multiple symbols to be defined.
See here for an example:
Static member initialization in a class template
Optionally, move all your constants to .cpp file without declaration in .h file. Use anonymous namespace to make them invisible beyond the cpp module.
// MyClass.cpp
#include "MyClass.h"
// anonymous namespace
namespace
{
string RE_ANY = "([^\\n]*)";
string RE_ANY_RELUCTANT = "([^\\n]*?)";
}
// member function (static or not)
bool MyClass::foo()
{
// logic that uses constants
return RE_ANY_RELUCTANT.size() > 0;
}