Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can two classes see each other using C++?

Tags:

So I have a class A, where I want to call some class B functions. So I include "b.h". But, in class B, I want to call a class A function. If I include "a.h", it ends up in an infinite loop, right? What can I do about it?

like image 825
Asj Avatar asked Dec 03 '09 01:12

Asj


People also ask

Can we define two classes in C Plus Plus?

You cannot have two classes directly contain objects of the other type, since otherwise you'd need infinite space for the object (since foo has a bar that has a foo that has a bar that etc.) Notice that the two headers don't include each other.

Can two classes have same name in C++?

It violates One Definition Rule.

Can two classes contain member functions with the same name?

Yes, but only if the two classes have the same name.


1 Answers

Put only member function declarations in header (.h) files, and put member function definitions in implementation (.cpp) files. Then your header files do not need to include each other, and you can include both headers in either implementation file.

For cases when you need to reference the other class in member signatures as well, you can use a forward declaration:

class A; 

This lets you use pointer and reference types (A* and A&), though not A itself. It also doesn't let you call members.

Example:

// a.h struct B; // forward declaration  struct A {    void foo(B* b); // pointers and references to forward-declared classes are ok };   // b.h struct A; // forward declaration  struct B {    void bar(A& a); // pointers and references to forward-declared classes are ok };   // a.cpp #include "a.h" #include "b.h"  void A::foo(B* b) {    b->bar(*this); // full declaration of B visible, ok to call members now }   // b.cpp #include "a.h" #include "b.h"  void B::bar(A& a) {    a.foo(this); // full declaration of A visible, ok to call members now } 
like image 176
Pavel Minaev Avatar answered Oct 25 '22 00:10

Pavel Minaev