1

I'm trying to create header and class files for two interdependent classes. I tried using #pragma once, extern class declaration, declaring classes in each other's headers. None of them seem to work. Here's my sample code:

A.h

#pragma once
#include "B.h"

class A
{
    private:
        int num;
    public:
        A();
        void printB(B b);
        int getA();
        ~A();
};

A.cpp

#pragma once
#include "stdafx.h"
#include "A.h"
#include <iostream>


A::A()
{
    num = 5;
}

void A::printB(B b)
{
    std::cout << "b = " << b.getB()  << std::endl;
}

int A::getA()
{
    return num;
}

A::~A()
{
}

B.h

#pragma once
#include "A.h"
class B
{
    private:
        char ch;
    public:
        B();
        void printA(A a);
        char getB();
        ~B();
};

B.cpp

#pragma once
#include "stdafx.h"
#include <iostream>
#include "B.h"


B::B()
{
    ch = 'g';
}

void B::printA(A a)
{
    std::cout << "a = " << a.getA() << std::endl;
}

char B::getB()
{
    return ch;
}

B::~B()
{
}

Interedependency.cpp [Entry point/ Main file]

#pragma once
#include "stdafx.h"
#include "A.h"


int main()
{
    A a;
    B b;
    a.printB(b);
    b.printA(a);
    return 0;
}

How to handle such interdependent classes in Visual Studio?

Jarod42
  • 203,559
  • 14
  • 181
  • 302
  • i think you should look at forward declaring a class instead of including the header e.g. class B; class A { ... }; then in a.cpp include "b.h" – AndersK May 09 '18 at 04:53
  • Possible duplicate of [Resolve build errors due to circular dependency amongst classes](https://stackoverflow.com/questions/625799/resolve-build-errors-due-to-circular-dependency-amongst-classes) – 1201ProgramAlarm May 09 '18 at 04:57
  • This has nothing to do with visual studio, it's a C++ question (not even c++11). – Moshe Gottlieb May 09 '18 at 05:06
  • `#pragma once` is only useful for header (cpp file are not included). – Jarod42 May 09 '18 at 08:12

1 Answers1

0

Don't include A.h or B.h in your headers, instead, forward declare A in B.h and B in A.h.
In your cpp files, include A.h from B.cpp and B.h from A.cpp.

In A.h - replace #include "B.h" with class A; - this tells the compiler we'll be using the class A, but we'll provide the details later.
The compiler only cares for class sizes at this point (in your case).
In the cpp file, include B.h to actually tell the compiler what B is all about, as you're going to actually use it.
Do the same for B.h and B.cpp - replacing the include with a forward declaration in the header, and including the other header in the source file.

Additionally, there is no need for #pragma once in the cpp files, these are already compiled once.

Moshe Gottlieb
  • 3,963
  • 25
  • 41