Created
June 17, 2022 16:41
-
-
Save jinpa-t/a778a580430f92abb12f716aaaa5c76b to your computer and use it in GitHub Desktop.
Forward Declaration of class in C++.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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(); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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"; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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