Skip to content

Instantly share code, notes, and snippets.

@jinpa-t
Created June 17, 2022 16:41
Show Gist options
  • Save jinpa-t/a778a580430f92abb12f716aaaa5c76b to your computer and use it in GitHub Desktop.
Save jinpa-t/a778a580430f92abb12f716aaaa5c76b to your computer and use it in GitHub Desktop.
Forward Declaration of class in C++.
#include "a.h"
#include "b.h"
std::string A::name() {
return "class A";
}
void A::check(B* b) {
std::cout << "From class A: object is from ";
b->name();
}
#include <iostream>
#ifndef a_h
#define a_h
#include "b.h"
class B;
class A {
public:
A()= default;
std::string name();
void check(B* b);
};
#endif // end a_h
#include "b.h"
#include "a.h"
void B::check(A& a) {
std::string name = a.name();
std::cout << "From class B: object is from " << name << std::endl;
}
B::~B() {
std::cout << "B object destroyed\n";
}
void B::name() {
std::cout << "class B\n";
}
#ifndef b_h
#define b_h
#include <iostream>
#include "a.h"
class A;
class B {
public:
void name();
void check(A& a);
~B();
};
#endif // end b_h
// we can include both 'a.h' and 'b.h' or either one
#include <iostream>
#include "b.h"
#include "a.h"
using namespace std;
int main() {
cout<<"Forward Declaration in C++" << endl;
B *b = new B;
A a;
b->check(a);
a.check(b);
delete b; // without this the object b is not destroyed
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment