Initializer list Question

The Partridge Family were neither partridges nor a family. Discuss.
Post Reply
Ross91
Posts: 4
Joined: July 31st, 2018, 8:33 am

Initializer list Question

Post by Ross91 » September 19th, 2018, 3:44 pm

I'm just beginning the Fart-Annoyed project.

I had an annoying problem with the initailizer list that took me ages to discover and fix.

I don't fully understand why it didn't work, stepping through i could see it working. it would initialise the top constructor, but then it would reset because it would return to the previous constructor body.

some clarification to help me understand would be appreciated :)

here are the two versions.

Updated:

Code: Select all

Rect::Rect(int left, int right, int top, int bottom)
	:
	left(left),
	right(right),
	top(top),
	bottom(bottom)
{
}

Rect::Rect(Vec2 & topleft, Vec2 & botright)
	:
	Rect(int(topleft.x), int(botright.x), int(topleft.y), int(botright.y))
{
}

Rect::Rect(Vec2 & topLeft, int width, int height)
	:
	Rect(topLeft, Vec2((topLeft.x + width), (topLeft.y + height)))
{
}
Previous:

Code: Select all

Rect::Rect(int left, int right, int top, int bottom)
	:
	left(left),
	right(right),
	top(top),
	bottom(bottom)
{
}

Rect::Rect(Vec2 & topleft, Vec2 & botright)
{
	Rect(int(topleft.x), int(botright.x), int(topleft.y), int(botright.y))
}

Rect::Rect(Vec2 & topLeft, int width, int height)
{
	Rect(topLeft, Vec2((topLeft.x + width), (topLeft.y + height)))
}

albinopapa
Posts: 4373
Joined: February 28th, 2013, 3:23 am
Location: Oklahoma, United States

Re: Initializer list Question

Post by albinopapa » September 19th, 2018, 7:23 pm

The answer lies in the title of your question really. In the "previous" code, you are using the function body and would need: *this = Rect{ topLeft, Vec2{ ( topLeft.x + width ), ( topLeft.y + height ) } };

The initializer list is exactly that, it initializes members of the class. So moving the constructor call to the initialzier list will still be initializing the current class, while moving it to the function body means the object is initialized and at that point, the constructor is basically just another function...without a return value ( or implicit reference to class return value if it helps ).
If you think paging some data from disk into RAM is slow, try paging it into a simian cerebrum over a pair of optical nerves. - gameprogrammingpatterns.com

Post Reply