...
In this noncompliant code example, the member initializer list for C::C() attempts to initialize SomeVal first and then to initialize DependsOnSomeVal dependsOnSomeVal to a value dependent on SomeValsomeVal. Because the declaration order of the member variables does not match the member initializer order, attempting to read the value of SomeVal someVal results in an unspecified value being stored into DependsOnSomeVal dependsOnSomeVal.
| Code Block |
|---|
|
class C {
int DependsOnSomeValdependsOnSomeVal;
int SomeValsomeVal;
public:
C(int val) : SomeValsomeVal(val), DependsOnSomeValdependsOnSomeVal(SomeValsomeVal + 1) {}
}; |
Compliant Solution
...
| Code Block |
|---|
|
class C {
int SomeValsomeVal;
int DependsOnSomeValdependsOnSomeVal;
public:
C(int val) : SomeValsomeVal(val), DependsOnSomeValdependsOnSomeVal(SomeValsomeVal + 1) {}
};
|
Note that it is reasonable for initializers to depend on previously initialized values.
...
| Code Block |
|---|
|
class B1 {
int Valval;
public:
B1(int Vval) : Valval(Vval) {}
};
class B2 {
int OtherValotherVal;
public:
B2(int VotherVal) : OtherValotherVal(VotherVal) {}
int getOtherValget_other_val() const { return OtherValotherVal; }
};
class D : B1, B2 {
public:
D(int A) : B2(A), B1(getOtherValget_other_val()) {}
}; |
Compliant Solution
...
| Code Block |
|---|
|
class B1 {
int Valval;
public:
B1(int Vval) : Valval(Vval) {}
};
class B2 {
int OtherValotherVal;
public:
B2(int VotherVal) : OtherValotherVal(VotherVal) {}
};
class D : B1, B2 {
public:
D(int A) : B1(A), B2(A) {}
}; |
...