[C++ Common Mistake] Class Members in Initialization Lists

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.


要查看或添加评论,请登录

Manojkumar Gupta的更多文章

社区洞察

其他会员也浏览了