Reputation: 711
I have a class in A.h file:
class A {
...
public:
A();
...
private:
bool t = false;
...
}
In the A.cpp file:
A::A() {
...
t = true; <- after this point, have t be const or readonly
...
}
Is this possible? Or would I have to use a different value?
Upvotes: 1
Views: 1475
Reputation: 55395
In-class initialization of members works in C++11:
class A {
public:
A();
private:
const bool t = false;
};
Before C++11, you'd use member initializer list:
class A {
public:
A() : t(false) {}
private:
const bool t;
};
But const
data members are unusual thing. For one, they make your class non-assignable (if you rely on compiler generated assignment operator). Just have the member private and don't let the interface provide the means to change it.
Upvotes: 2
Reputation: 96251
Unfortunately you can't do it in this way.
However you can still do what you want to do (you can change the exact mechanism to suit your precise needs since you weren't quite clear):
class A {
...
public:
A();
...
private:
bool A::init_A_impl();
const bool t_;
...
};
bool A::init_A_impl()
{
bool t = false;
...
t = true; <- after this point, have t be const or readonly
...
return t;
}
A::A() : t_(init_A_impl())
{
}
Upvotes: 2