How to initialize a const field in constructor?
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) {
}
Initializing const members and other special cases (such a parent classes) can be accomplished in the initializer list
class Foo {
private:
const int data;
public:
Foo(int x) : data(x) {}
};
Or, similarly, for parent initialization
class Foo {
private:
int data;
public:
Foo(int x) : data(x) {}
};
class Bar : Foo {
public:
Bar(int x) : Foo(x) {}
};
You need to initialize foo in the initializer list.
class Bar {
Foo* const foo;
public:
Bar(Foo* f) : foo(f) {...}
};