0

I have two classes. Class A contains a pointer to an instance of class B. In class A, I would like to call class B's instance method and send class A itself as the argument. I wrote the following code but it doesn't compile:

Source for Class A:

//a.h
#ifndef A_H
#define A_H

#include "b.h"

class A{
  friend class B;
  int i;

  B *b;

public:
  void callB(){b->calledByA(this);}
};

#endif

Source for Class B:

#ifndef B_H
#define B_H

#include "a.h"

class B{
  int j;

public:
  void calledByA(A* a){
    //j=a.i;
  }
};

#endif

The error given by VS 2010 is

error C2061: syntax error : identifier 'A'
error C2660: 'B::calledByA' : function does not take 1 arguments

Why?

shapeare
  • 4,133
  • 7
  • 28
  • 39

3 Answers3

4

On your example, assuming you include b.h first, in a.h B is not defined yet so b->calledByA(this); won't compile. But you can place this in the .cc file and this will work.

//a.h
#ifndef A_H
#define A_H

class B;

class A {
  friend class B;
  int i;

  B *b;

public:
  void callB();
};

#endif

Source for class A:

// a.cc
#include "a.h"
#include "b.h"

void A::callB() {
  b->calledByA(this); 
}

Source for Class B:

#ifndef B_H
#define B_H

#include "a.h"

class B {
  int j;

public:
  void calledByA(A* a){
    j = a.i;
  }
};

#endif
Nicolas Defranoux
  • 2,646
  • 1
  • 10
  • 13
1

You have a circular dependencies. To avoid this you have to forward declare one class :

Class B

#ifndef B_H
#define B_H

#include "a.h"

class A; // Here you pre-defined class A until it is known for the compiler

class B{
  int j;

public:
  void calledByA(A* a){
    //j=a.i;
  }
};
Yabada
  • 1,728
  • 1
  • 15
  • 36
0

What you want to do is not a good design, since circular dependencies should be avoided. Still it is entirely possible in C++, and the best way is to split your files into .h and .cpp files. In .h you need only class declarations without method definitions. In .cpp you put method definitions. If a class needs to refer to another class, use forward declaration like

class A;
Wojtek Surowka
  • 20,535
  • 4
  • 44
  • 51