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.
A constructor can initialize an object that has been declared as const , volatile or const volatile .
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 .
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.
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"; };
You need to do it in an initializer list:
Bar(Foo* _foo) : foo(_foo) { }
(Note that I renamed the incoming variable to avoid confusion.)
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) { }
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