Nathan
Nathan

Reputation: 78439

C++ classes using eachother

I have two classes, lets say Class A and Class B. My goal is to have both classes use eachothers functions. Problem is, the multi-file include structure doesn't seem to let me do that. Here's what I'm trying to do:

#file A.h

Class A{
public:
    int GetInfo();

private:
    B * ptrToB;
};

#file B.h

Class B{
public:
   int getStuff();
private:
   A * ptrToA;
};

My goal is for an A class method to be able to call ptrToB->getStuff() and for a B class method to be able to call ptrToA->getInfo()

Is this possible? How so? If not, why not?

Upvotes: 2

Views: 2066

Answers (3)

BЈовић
BЈовић

Reputation: 64223

You can use forward declaration to break dependencies :

#file A.h

Class A{
public:
    int GetInfo();

private:
    B * ptrToB;
};

#file B.h
struct A;
Class B{
public:
   int getStuff();
private:
   A * ptrToA;
};

Then you can include A.h in B.cpp and B.h in A.cpp without problems.

Upvotes: 2

Connor Hollis
Connor Hollis

Reputation: 1155

Maybe using forward declarations?

#file A.h

#ifndef ACLASS_H
#define ACLASS_H

Class B;

Class A{
public:
    int GetInfo();

private:
    B * ptrToB;
};

#endif

Then in the CPP file.

#file A.cpp

#include "B.h"

A::A() : ptrToB(0)
{
  // Somehow get B
}

int A::GetInfo() 
{
  // Return whatever you need in here.
}

The same thing would be done for the B classes H and CPP files.

A forward definition allows the compiler to recognize a type without needed it explicitly defined. If you had a reference to a B in the A class you would have to include B's header.

Since you are using a pointer to access B the compiler does not need to know the internal data until you access it (inside the CPP file).

// Would need the header because we must know 
// the size of B at compile time.
class B;
class A 
{
  B theB; 
}


// Only need forward declaration because a 
// pointers size is always known by the compiler
class B;
class A
{
  B * bPointer; 
}

Upvotes: 4

danielschemmel
danielschemmel

Reputation: 11116

Just add a forward declaration to file A.h, so the compiler knows that a B* is a pointer to a class you will define later on:

class B;

Then define your class A and include B.h after that. This way anybody including A.h will have both class A and class B defined.

In B.h just include A.h at the beginning. This way anybody including B.h will also have both class A and class B defined.

When you define your functions in the associated .cpp files, you will have both classes available, and can just write your functions as you want to.

This problem is called mutual recursion.

Upvotes: 2

Related Questions