How to initialize a const field in constructor?


Question

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.

1
65
10/30/2010 9:19:24 AM

Accepted Answer

You need to do it in an initializer list:

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

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

77
9/14/2009 8:24:13 PM

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) {
}

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon