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?