Initializing a const member variable after object

2020-07-29 23:34发布

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++ constants
1条回答
贪生不怕死
2楼-- · 2020-07-30 00:00

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;
}
查看更多
登录 后发表回答