POV-Ray : Newsgroups : povray.off-topic : Teach yourself C++ in 21 days : Re: Days 1-5 Server Time
29 Jul 2024 22:22:09 EDT (-0400)
  Re: Days 1-5  
From: Warp
Date: 20 Apr 2012 10:15:30
Message: <4f916f82@news.povray.org>
Invisible <voi### [at] devnull> wrote:
> >    The only thing that's impossible for a class to have another class
> > as member variable, and that another class having the first class as
> > member variable.

> Yeah, that's exactly what I'm trying to do.

  I don't think so.

> Actually, no, wait... Class X has class Y as a member, but class Y only 
> /mentions/ class X. (It has member functions that return objects of 
> class X.)

  Sounds like a rather complicated design. Anyways, you can declare classes
(as opposed to defining them). In other words, you can do this:

//----------------------------------------
// This could be eg. in a "Y.hh" header file
class X; // declaration of X

class Y
{
 public:
    void foo() { std::cout << "I'm an Y\n"; }
    X gimmeAnX();
};
//----------------------------------------

  You can then define X for example like:

//----------------------------------------
// This could be eg. in a "X.hh" header file,
// in which case you would have a
// #include "Y.hh" here.
class X
{
    Y anObjectOfY;

 public:
    void bar() { anObjectOfY.foo(); }
};
//----------------------------------------

  After both definitions you can now implement the Y::gimmeAnX() function,
eg. like:

//----------------------------------------
// This could be eg. in a "Y.cc" source file,
// in which case you would have a
// #include "X.hh" here.
X Y::gimmeAnX() { return X(); }
//----------------------------------------

  (All of the above code could be in one single source file as well,
in that order, which is why I didn't explicitly use any #include lines.)

> > (For obvious reasons. It would be an infinitely large class.)

> It can if at least one of the classes refers to the other through a 
> pointer or a reference.

  It wouldn't be a member variable then.

> So, the way I see it, I have two options:

> 1. Put class X and class Y in the same header file.

  Not necessary (and even if you put it in the same header file, that alone
wouldn't solve your problem).

> 2. Start throwing unchecked casts around the place.

  The correct solution is to use class declarations.

-- 
                                                          - Warp


Post a reply to this message

Copyright 2003-2023 Persistence of Vision Raytracer Pty. Ltd.