home bbs files messages ]

Forums before death by AOL, social media and spammers... "We can't have nice things"

   comp.lang.c++.moderated      Moderated discussion of C++ superhackery      33,346 messages   

[   << oldest   |   < older   |   list   |   newer >   |   newest >>   ]

   Message 31,355 of 33,346   
   =?ISO-8859-1?Q?Daniel_Kr=FCgler?= to All   
   Re: Question on forward declarations   
   29 May 11 01:38:36   
   
   889e003f   
   From: daniel.kruegler@googlemail.com   
      
   Am 28.05.2011 10:29, schrieb kelvSYC:   
   > I'm having trouble with where I should put in a forward declaration   
   > and/or whether I should redesign two classes that reference each   
   > other.   
   >   
   > Suppose I have two classes A and B.  A has a member function foo()   
   > returning a B, something like:   
   >   
   > B foo() const { return B(1, *this); }   
   >   
   > A does not have any references to B other than the one above.  B has a   
   > member of class A, from taking an A in its two-arg constructor; B is   
   > not default-constructible.  But oddly enough, when I try to add in   
   > "class B;" in A.h, the class B refuses to compile, and when I try to   
   > add in "class A;" in B.h, the class A refuses to compile.  Having said   
   > that, I have already included B.h and A.h in each other's files.   
   >   
   > Should I remove one of the #includes?  Which class should I forward   
   > declare?  Should I redesign B to use a pointer to the A instead?   
      
   There is no need for a pointer, the following design should work:   
      
   // Header a.h:   
   class B;   
      
   class A {   
   public:   
     B foo() const;   
   };   
      
   // Header b.h:   
   #include "a.h"   
      
   class B {   
     A a;   
   public:   
     B(int, A a) : a(a) {}   
   };   
      
   // Either in header b.h, or in a separate header (or .cpp)   
   // including b.h   
   inline B A::foo() const {   
     return B(1, *this);   
   }   
      
   HTH & Greetings from Bremen,   
      
   Daniel Krügler   
      
      
   --   
         [ See http://www.gotw.ca/resources/clcm.htm for info about ]   
         [ comp.lang.c++.moderated.    First time posters: Do this! ]   
      
   --- SoupGate-Win32 v1.05   
    * Origin: you cannot sedate... all the things you hate (1:229/2)   

[   << oldest   |   < older   |   list   |   newer >   |   newest >>   ]


(c) 1994,  bbs@darkrealms.ca