Advanced C++ Overloading the Arithmetic Operator

Hey all,

I’m just wondering if anyone managed to solve the topic in chapter 8 on the advanced course. After some work, I managed to get the, ahem, ‘basic’ one to work

The basic example is to be able to add an integer to a custom class (in this video, length) such as;

Length third = first + 4;

Mosh says to create a new overload taking an integer as the parameter. I found this really difficult
I tried declaration;

	Length operator+(const int other) const;

with a definition of

Length Length::operator+(const int other) const
{
	return int(value);
}

but of course, we can’t do that as 'no suitable constructor exists to convert in to Length. So then I tried

Length Length::operator+(const int other) const
{
	return Length((int (value)));
}

but this doesn’t reference the other value so for

Length first{ 10 };
Length second{ 20 };
int four = 4;

Length third = first + 4;
cout << third;

the answer is 10.
I finally tried

Length Length::operator+(const int other) const
{
	return Length((int (value))+ other);
}

and this works!! :grin:

But I really can’t get past the excercise and I dn’t really understand the question. I think we have to add Point(x,y) to a second Point(x,y) as well as the integers? (I think?)

Anyway, I tried, but could not get my head around this, with using 2 parameters. All of my trials were a disaster, so there’s no point in me even posting them. I was hoping someone who completed this exercise would be able to share the solution?

Screen Shot 2024-01-21 at 7.32.32 am