Need help on calling objects and parameter objects

So for say I have a function called commonType. In my main.cpp file there is a call and it looks like this:
pokemon1.commonType(pokemon2)

Now I am confused as what to do. I am suppose to compare the types the pokemon has and if the have a common type, I would print out yes and if not, it would be no.

so I am stuck since the error says cannot convert:
'bool Pokemon::commonType(Pokemon &)' : cannot convert 'this' pointer from 'const Pokemon' to 'Pokemon &'

this is my pokemon.cpp file
1
2
3
4
5
6
7
8
9
10
11
12
13
bool Pokemon::commonType(const Pokemon& pokemon2)
{
	if (type1 == pokemon2.type1)
		return true;
	else if (type1 == pokemon2.type2)
		return true;
	else if (type2 == pokemon2.type1)
		return true;
	else if (type2 == pokemon2.type2)
		return true;
	else
		return false;
}



and this is the main.cpp file that has that method:

1
2
3
4
5
6
7
8
9
void test(const Pokemon& pokemon1, const Pokemon& pokemon2)
{
	pokemon1.print();
	cout << endl;
	pokemon2.print();
	cout << "\n    Common type? "
		<< ((pokemon1.commonType(pokemon2)) ? "Yes" : "No");
	cout << "\n------------------------------\n";
}
You correctly mark the parameters with const when the function is not supposed to modify the objects that's being passed as arguments.

What you also need to do is to mark the member functions themselves with const when you don't want the function to modify the object that the function is called on.

1
2
3
4
5
6
7
8
9
10
11
class Pokemon
{
public:
	bool commonType(const Pokemon&) const;
	...
};

bool Pokemon::commonType(const Pokemon& pokemon2) const
{
	...
}
Last edited on
Oh okay, makes sense now. Thank you for the explanation. It works
Topic archived. No new replies allowed.