So ive been asked to create a friend of a function for a university class and im a bit lost on the implementation. The question states "Add a function showCat(Cat&) as a friend of Cat. This function should display the cat details in the same way as the Cat::showCat() function does"
The program is as follows
#include<iostream>
#include<string>
using namespace std;
class Cat
{
private:
string name;
string breed;
int age;
static constexpr double licenseFee = 10;
public:
void setCatData(string, string, int);
void showCat();
friend void showCat(const Cat& cat); //friend function declaration
};
void Cat::setCatData(string catName, string catBreed, int catAge)
{
name = catName;
breed = catBreed;
age = catAge;
}
void Cat::showCat(const Cat& aCat) //friend function definition
{
cout << "Cat: " << aCat.name << " is a " << aCat.breed << endl;
cout << "The cat's age is " << aCat.age << endl;
cout << "License fee: $" << aCat.licenseFee << endl;
}
void Cat::showCat()
{
cout << "Cat: " << name << " is a " << breed << endl;
cout << "The cat's age is " << age << endl;
cout << "License fee: $" << licenseFee << endl;
}
int main()
{
Cat myCat;
myCat.setCatData("Tigger", "Fluffy unit", 3);
myCat.showCat();
}
The provided notes arent spectacular but this was my attempt based on the information provided to me. My attempt at the friend function can be seen in the declaration friend void showCat(const Cat& cat);
in the public members of the cat class. The defintion can be seen as
void Cat::showCat(const Cat& aCat)
{
cout << "Cat: " << aCat.name << " is a " << aCat.breed << endl;
cout << "The cat's age is " << aCat.age << endl;
cout << "License fee: $" << aCat.licenseFee << endl;
}
This where my errors stem from. On the line void Cat::showCat(const Cat& aCat)
I get
declaration is incompatible with "void Cat::showCat()" (declared at line 34)
Im a bit lost to how friends operate so any help to fix my function/program would be appreciated :)
The declaration
friend void showCat(const Cat& cat);
declares showCat(const Cat&)
as a non member function.
So you need to define it as such:
// Note that this is not a member function
void showCat(const Cat& aCat)
{
...
}