class Foo {
private:
int m_i;
public:
Foo(int i) : m_i(i) {}
};
class FooA
{
private:
const static Foo & m_foo;
static Foo & m_foo2;
};
Q1> how to initialize const static reference?
Q2> How to initialize non-const static reference?
Note: You can make changes for class FooA in order to illustrate the methods.
No. A reference is simply an alias for an existing object. const is enforced by the compiler; it simply checks that you don't attempt to modify the object through the reference r .
To initialize the const value using constructor, we have to use the initialize list. This initializer list is used to initialize the data member of a class. The list of members, that will be initialized, will be present after the constructor after colon. members will be separated using comma.
We can put static members (Functions or Variables) in C++ classes. For the static variables, we have to initialize them after defining the class. To initialize we have to use the class name then scope resolution operator (::), then the variable name. Now we can assign some value.
You initialize const and non-const static references the same way you would initialize any static member: by putting the initialization in the global scope. const Foo& FooA::m_foo = ... whatever... Foo& FooA::m_foo2 = ...
In the same way you initialize non-reference static
members:
//Foo.cpp
const Foo & FooA::m_foo = fooObj1;
Foo & FooA::m_foo2 = fooObj2;
where fooObj1
and fooObj2
are global variables of type Foo
.
Note fooObj1
and fooObj2
must be initialized before m_foo
and m_foo2
, otherwise you might face static initialization order fiasco problem.
The same way as any other static data member:
Foo foo(5);
const Foo& FooA::m_foo(foo);
Foo& FooA::m_foo2(foo);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With