Question on Chapter 3

Volume I - Foundations

Question on Chapter 3

Postby misterweels » Mon Jul 23, 2012 11:54 pm

This question is more on C++ than it is on boost. In your example for boost signals page 41, you define an "Observable" class and an "Observer" class.



There is an instance of observer inside Observable.



class Observable

{

list<Observer*> Observers;

...

}



on page 42 you have



class Observer

{

...

virtual void Update(Observable& obj);

}



when you build these classes in a single file or in separate files i always get a compile error saying "the class must be known." Observable needs to know the class Observer before it can be used and vice versa.



How do you overcome this? I've had problems following other examples like this before and i just never understood how to work around it.



Thanks
misterweels
 
Posts: 6
Joined: Sun Jul 22, 2012 6:22 am

Postby admin » Wed Jul 25, 2012 10:58 am

If you have circular references (class A refers class B and class B refers class A), you need to use a forward declaration. Thus in the header file of class A, you forward declare class B instead of including it.



Code: Select all

// A.hpp



#ifndef A_hpp

#define A_hpp



class B; // Forward declaration of class B.



class A

{

public:

  void F(const B& b);

};



#endif







And in "B.hpp" you can just include "A.hpp".

Code: Select all

// B.hpp



#ifndef B_hpp

#define B_hpp



#include "A.hpp"



class B

{

public:

  void F(const A& a);

};



#endif







In the source files you can include the header files as normal.

When there are circular references, you can't put the two classes in the same file and you also need a separate source and header file.



Robert
admin
Site Admin
 
Posts: 237
Joined: Thu Dec 07, 2006 4:03 pm
Location: Amsterdam, The Netherlands


Return to Introduction to the Boost C++ Libraries - Volume I (Demming/Duffy)

Who is online

Users browsing this forum: No registered users and 1 guest

cron