Constructors C++, What does the colon after a constructor mean? [duplicate]

StackOverflow https://stackoverflow.com/questions/23548367

  •  18-07-2023
  •  | 
  •  

Вопрос

Skimming through some code I noticed something I honestly can't wrap my head around in a constructor.
class Terrain { public: Terrain(int movementCost, bool isWater, Texture texture) : movementCost_(movementCost), isWater_(isWater), texture_(texture) {} ... //More code
What sort of wizardry is this? Are those foo_(foo) representing foo = foo_?

Это было полезно?

Решение

This is a c++ initialiser list. You have it almost right, foo_(foo) is equivalent to foo_ = foo;

This is useful for when you have a member variable that does not have a default constructor. Without this feature, you would have to make it a pointer.

The initialisations are also executed in the order that the members were declared in the class defenition, not the order they appear in (which should be the same as a matter of style, but isn't necessarily)

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top