2

I often find myself wishing I could have an object's member variable be const, but that the system allowed initialization of that const variable after construction. Is there a mechanism that would allow me to do this?

To clarify, here is an example:

class A
{
public:
    A(){}
    initialize(int x) { c = x; }
private:
    const int c;
}

I want to be able to do something like that. I don't have this information at construction, so I can't simply move initialization to the initialization list of the constructor.

c.hughes
  • 284
  • 1
  • 13
  • 1
    I don't think there's a way to do it using the const keyword specifically. You'd probably have to use some kind of flag indicating if the value has been initialized and allow or not allow changes to be made based on that – Eric B Nov 19 '12 at 16:59

1 Answers1

5

No, you cannot initialize const member after contruction.

Do not forget, however, that you can call static functions in initializer list, so in most of cases you can initialize memebers from initializer list

class A
{
public:
    A(){}
    initialize(int x):c(computeC(x)) {}
private:
    const int c;
    static int computeC(int){/*...*/}
};

You can also define special getter for that member and use it to access member.

class A
{
public:
    A(){}
    initialize(int x) { c_internal = x; }
private:
    const int& c() const { return c_internal; }
    int c_internal;
}
Lol4t0
  • 12,444
  • 4
  • 29
  • 65