Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize const / non-const static reference member?

Tags:

c++

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.

like image 827
q0987 Avatar asked Aug 16 '11 05:08

q0987


People also ask

Can a const reference be bound to a non const object?

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 .

How do I initialize const member?

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.

How do you initialize a static member?

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.

How do you initialize a static reference in C++?

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 = ...


2 Answers

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.

like image 84
Nawaz Avatar answered Sep 29 '22 16:09

Nawaz


The same way as any other static data member:

Foo foo(5);
const Foo& FooA::m_foo(foo);
Foo& FooA::m_foo2(foo);
like image 44
hamstergene Avatar answered Sep 29 '22 15:09

hamstergene