Jichao
Jichao

Reputation: 41805

How to use a reference variable in a C++ class?

I want to have a reference data member in a class, but I do not want to initialize it in the constructor.

How could I do this?

Upvotes: 1

Views: 140

Answers (3)

Aesthete
Aesthete

Reputation: 18848

As mentioned before, this is often a poor idea, if a reference is required somewhere - there is usually a solid reason as to why.

If there is a specific reasoning for what you're doing though, you may want to have a look at Null Object Patterns.

You can make a null object that throws some sort of 'not implemented' exception, or does nothing at all. You are still going to have to initialize your member variable in the initializer list, but now at least you have some flexibility to make changes in the future.

Upvotes: 0

Ajay
Ajay

Reputation: 18411

You must initialize it in the constructor (only through initializer-list), since that's the attribute of a reference-variable (references must be initialized).

You may initialize it to some static/global variable by keeping it inialized by default parameter.

YourClass::YourClass(int& ref = _SomeGlobalVar) : m_RefInClass(ref){}

But you wont be able to re-initialize it further.

Upvotes: 2

Asha
Asha

Reputation: 11232

That is not possible, you have to initialize reference data members inside ctor initialization list. If you really have to do something like this, use a pointer to the data member instead of reference. Initialize pointer to NULL in ctor and then initialize it correctly whenever you want.

Upvotes: 10

Related Questions