Question

So to toy with friend functions, I decided to make a Child class and a Mother class. The Mother class has a data member that is a Child. The Child class makes two methods of the Mother class friend functions.

When I compile though, it seems that no matter how I handle inclusions I end up with an error. If the Child is the first one to get defined, I get "Mother is not a class or namespace name" for the line friend void Mother::setChildName(string name); in Child.h. If the Mother is the first one to get defined, I get "Missing type specifier" for the line Child c; in Mother.h.

Is there a way around this? I tried putting class Mother; at the top of the Child.h and class Child; at the top of Mother.h and that didn't seem to help.

Or is this kind of circular reference just always going to fail?

In Mother.h:

#ifndef MOTHER_H_
#define MOTHER_H_

#include <string>
#include "Child.h"

using namespace std;

class Mother {
public:
    Mother();

    void setChildName(string name);

    string getChildName();

private:
    Child c;
};

#endif

In Mother.cpp:

#include <string>
#include "Mother.h"

using namespace std;

void Mother::setChildName(string name) {
    c.name = name;
}

string Mother::getChildName() {
    return c.name;
}

In Child.h:

#ifndef CHILD_H_
#define CHILD_H_

#include <string>
#include "Mother.h"

using namespace std;

class Child {
public:

private:
    string name;

    friend void Mother::setChildName(string name);
    friend string Mother::getChildName();
};

#endif
Was it helpful?

Solution

This particular problem cannot be solved without redesign. Mother needs to be defined before Child, and Child needs to be defined before Mother. The simple way is to make the whole Mother class a friend of Child. That way Child can be defined first.

I think there little practical benefit in making individual methods friends of another class. That would imply that your class is so big that it's responsibilities could be divided into smaller classes.

OTHER TIPS

if Mother will hold pointer to child, you will not have to include child.h. forward deceleration will be enough.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top