Object relationship

18.5 - Association


One type of relationship between objects is relationship. A relationship between object is formed when one object has a pointer to the other object but not necessarily owning it. For example you might have a friendly relationship with your friend, but your friend can still exist without you (hopefully).

Put into code, your (Tom) relationship with your friend (Jerry) might look like this:

#include <iostream>

class Person
{
public:
    Person(std::string name)
    :   name(name)
    ,   ally(nullptr)
    {}

    std::string name;
    Person* ally;
};

int main()
{
    Person tom("Tom");
    Person jerry("Jerry");

    tom.ally = &jerry;
    jerry.ally = &tom;

    std::cout << tom.name << "'s friend is " << tom.ally->name << std::endl;
    std::cout << jerry.name << "'s friend is " << jerry.ally->name << std::endl;
}

Your task is to complete the Cat class in the below code. It should have the following members:

  • name (string)
  • ally (pointer to another Cat object)
  • Cat (the constructor, it should accept a string which is set as the name)
  • introduce (a void function which describes the cat like in the example)

Sample code input

int main()
{
    Cat tem("Temmie");
    Cat tom("Tom");
    Cat meowth("Meowth");

    tem.ally = &tom;
    tom.ally = &tem;

    tem.introduce();
    tom.introduce();
    meowth.introduce();
}

Sample output

Hoii!! I'm Temmie!!!
And dis is my friend Tom!!!
Hoii!! I'm Tom!!!
And dis is my friend Temmie!!!
Hoii!! I'm Meowth!!!
And Meowth has no friend :(
#include <iostream> #include <string> class Cat { public: // Complete this class! };