Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize a const member without a copy constructor with a given value? [duplicate]

Possible Duplicate:
How to initialize a const field in constructor?

I have this class:

class Foo {
private:
    ...
public:
    Foo() : ... {}
    // no other constructors
    ...
};

and another one which holds a Foo member by reference:

class Bar {
private:
    const Foo& m_foo;
    ...
public:
    Bar(const Foo& foo);
    // no other constructors
};

My question is: how do i initialize the Bar::m_foo reference at the constructor?

Thanks!

like image 221
uv_ Avatar asked Jun 29 '26 04:06

uv_


1 Answers

In the constructor initialization list:

Bar(const Foo& foo) : m_foo(foo)
{
}

const and reference members must be initialized in the initialization list, in this case the member is both.

like image 92
Luchian Grigore Avatar answered Jul 01 '26 18:07

Luchian Grigore