0

I have two classes, one and two, each having a friend member function with an pointer to the other. The first header file is as per below:

#ifndef FIRSTCLASS_H
#define FIRSTCLASS_H

class two;

class one {

private:
int one_data;

public:
friend void second_data (two *);
};

#endif

The second header file looks like this:

#ifndef SECONDCLASS_H
#define SECONDCLASS_H

class one;

class two {

private:
int two_data;

public:
friend void first_data (one *);
};

#endif

The actual functions are in a third .cpp file. I wrote the functions with appropriate class qualifier, it gives an compilation error. I am using g++. The functions are as follows:

#include "firstclass.h"
#include "secondclass.h"

void two::first_data (one * class1) {

}

 void one::second_data (two * class2) {

}

The errors are as followa:

 error:no ‘void two::first_data (one*)’ member function declared in class ‘two’ 
 error: no ‘void one::second_data(two*)’ member function declared in class ‘one’

When I drop the class qualifier before the function name, the code compiles. The modified functions are as follows:

 void first_data(one * class1) {

 }

 void second_data(two * class2) {

 }

I am new to c++ and I am not sure if I am doing anything wrong in the first case. Please enlighten me.

maths-help-seeker
  • 946
  • 1
  • 10
  • 30

2 Answers2

5

What you declare is freestanding functions as friends of your classes.
They are not really members of any class.

friend void first_data (one *); 

declares a freestanding function first_data as friend of your class, it does not mean first_data is a member function of your class. Hence when you define the function in cpp file the compiler complains that the function was never declared.

Also,

void two::first_data (one * class1){}

Returntype ClassName ScopeResolution FunctionSignature

two:: tells compiler the functions belongs to this particular class, it is not namespace specification, it is class qualification.

Alok Save
  • 202,538
  • 53
  • 430
  • 533
2

That's not a namespace, that's a class qualifier.

void two::first_data (one * class1) {

}

defines the method first_data from class two.

However, you declared as friend the free function first_data:

friend void first_data (one *);

which is not the same. If you want free functions as friends, use the friend declaration you already have. If not, you can declare methods as friends similary:

friend void two::first_data (one *);
Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625