0

While tryin some stuff I wanted to make an example using c++ shell online which has only 1 file.

I tried making an example where you pass this by reference like this:

// Example program
#include <iostream>
#include <string>
class B;
class A{
public:
   void passMe(){
       B b;
       b->handle(*this);
       };

       void runMe(){
           std::cout << "Did run. ";
       };
};

class B{
public:
    void handle(A& refer){
        refer.runMe();
        };
};

int main()
{
  A a;
  a.passMe();
}

But I have a circular reference. Normaly you would foreward declare (with an include in the cpp file) but as far as I know thats not posible in the example given (where you need to use 1 file).

Are there other options to make the example code work?

Sven van den Boogaart
  • 11,833
  • 21
  • 86
  • 169
  • https://stackoverflow.com/questions/625799/resolve-header-include-circular-dependencies-in-c – πάντα ῥεῖ Aug 27 '16 at 20:08
  • @πάνταῥεῖ im not asking how to forward declare but how to solve the situation where you have circular reference in a single file.. – Sven van den Boogaart Aug 27 '16 at 20:09
  • To start with: You cannot use a member `B b;` from a forward declaration. Read up from my link, it's all well explained there. I would have dupe hammered your question, just out of votes today. – πάντα ῥεῖ Aug 27 '16 at 20:11
  • Having function definitions inline in class definitions is an unnecessary complication. Moving those out of `A` makes this trivial. – molbdnilo Aug 27 '16 at 20:12

1 Answers1

4

How to solve it? Fix the typos and define passMe later.

#include <iostream>
#include <string>

class A{
public:
   void passMe();
   void runMe(){
      std::cout << "Did run. ";
       };
};

class B{
public:
    void handle(A& refer){
        refer.runMe();
        };
};

void A::passMe() {
    B b;
    b.handle(*this);
}

int main()
{
  A a;
  a.passMe();
}
KIIV
  • 3,534
  • 2
  • 18
  • 23