Simple OO question.

Started by
3 comments, last by xegoth 18 years, 4 months ago
My C++ is unfrotunately a bit rusty and I've run into a problem I don't remember how to get around. If you have the following layout:

//A.h

#ifndef _A_H_
#define _A_H_

#include "B.h"
class A
{
   A()
   {
        b = new B(this); 
   }

  B b;
}

#endif



//B.h
#ifndef _B_H_
#define _B_H_

#include "A.h"
class B
{
  B(A &a);
}

#endif


The above code wouldn't compile because the line: B(A &a); A hasn't been defined yet. How do you get around a problem like this when you want a class to pass a reference of itself to a child?
Advertisement
/Edit: Ahem, Nothing to see here, just me making an idiot of myself :-)

Alan
"There will come a time when you believe everything is finished. That will be the beginning." -Louis L'Amour
//B.h#ifndef _B_H_#define _B_H_#include "A.h"class A;class B{  B(A &a);}#endif


By doing this you're telling the linker that there is a class A, but you'll give the definition later.
We should do this the Microsoft way: "WAHOOOO!!! IT COMPILES! SHIP IT!"
Quote:Original post by Alan Kemp
You can't solve this with references, you will have to use pointers.

*** Source Snippet Removed ***

Alan


I somewhat agree... Why not, though?

If you pass a reference of the value of this, it should work (like in this example of an overloaded operator):
Log &Log::operator <<(const string &Message) {    m_LogFile << Message;    return (*this);}

So, in your example it wold be:
b = new B((*this));

As for the other part, just foreward declare: (some random off-top-head code)
class X;class Y {    ...};class X { ... };

But then again, you'll have to fix that to go with your files ;).

Good luck!

C++
dbzprogrammer, yeah that's the answer. I just couldn't rememember. Thanks :)

This topic is closed to new replies.

Advertisement