[C++ Common Mistake] Class Members in Initialization Lists
Manojkumar Gupta
Engineering Manager | E-commerce | Recommendation & Observability System | Ex-Flipkart
Initialization lists are one of the preferred way to initialize member variable of a new class instance/Object.
class Foo
{
public:
Foo(int size) : _size(size),
_capacity( size + 2),
_length( _capacity)
{}
virtual void status()
{
std::cout << "Size: " << _size << " Capacity: " << _capacity << " Length: " << _length << std::endl;
}
private:
int _length;
int _capacity;
int _size;
};
int main()
Foo foo(50);
foo.status();
return 0;
}
What it prints is this,
Size: 50 Capacity: 52 Length: 0
Whats Wrong in above result,
We could see that _length is not initialized correctly. It should have been 50, Right?
Wrong, we missed something here,
Class members are initialized in the order they are declared, not the order specified in your initialization list. Since _length defined before other member variable hence it gets initialized first and that moment _capacity wasn’t initialized.