Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize a const field in constructor?

Imagine I have a C++ class Foo and a class Bar which has to be created with a constructor in which a Foo pointer is passed, and this pointer is meant to remain immutable in the Bar instance lifecycle. What is the correct way of doing it?

In fact, I thought I could write like the code below but it does not compile..

class Foo;  class Bar { public:     Foo * const foo;     Bar(Foo* foo) {         this->foo = foo;     } };  class Foo { public:   int a; }; 

Any suggestion is welcome.

like image 572
puccio Avatar asked Sep 14 '09 20:09

puccio


People also ask

Can const be initialized in constructor?

A constructor can initialize an object that has been declared as const , volatile or const volatile .

How do you declare and initialize a constant in C++?

A constant variable must be initialized at its declaration. To declare a constant variable in C++, the keyword const is written before the variable's data type. Constant variables can be declared for any data types, such as int , double , char , or string .

Does const need to be initialized?

When a variable is declared as const it means that , variable is read-only ,and cant be changed . so in order to make a variable read only it should be initialized at the time it is declared.

How do you initialize static constant characteristics of a class in C++?

For std::string , it must be defined outside the class definition and initialized there. static members must be defined in one translation unit to fulfil the one definition rule. If C++ allows the definition below; struct C { static const string b = "hi"; };


2 Answers

You need to do it in an initializer list:

Bar(Foo* _foo) : foo(_foo) { } 

(Note that I renamed the incoming variable to avoid confusion.)

like image 148
Jim Buck Avatar answered Sep 27 '22 19:09

Jim Buck


I believe you must do it in an initializer. For example:

Bar(Foo* foo) : foo(foo) { } 

As a side note, if you will never change what foo points at, pass it in as a reference:

Foo& foo;  Bar(Foo& foo) : foo(foo) { } 
like image 28
SingleShot Avatar answered Sep 27 '22 19:09

SingleShot