Boost logo

Boost Users :

Subject: Re: [Boost-users] [Boost.Python] Is it possible classes X Y returned each other?
From: Lars Viklund (zao_at_[hidden])
Date: 2012-06-29 09:52:44


On Fri, Jun 29, 2012 at 11:23:56AM +0300, Sergiy Nazarenko wrote:
> Hi, all!
> I'm writing python module and run into obstacle. I need a couple of classes
> which can return instance of each other.
> This is part of my module:
>
> /// mysupermodule.cpp
> ...
> struct X
> {
> X():s("default") {}
> X(std::string s):s(s) {}
> Y getY() const { return Y(); }
> };
>
> struct Y
> {
> Y():s("default") {}
> Y(std::string s):s(s) {}
> X getX() const { return X(); }
> };
> ...
> ///
> And I got obvious error: mysupermodule.cpp:45:5: error: ‘Y’ does not name
> a type.

This is not really related to Boost at all.

Anyway, what you need to do is two things - forward declare Y and define
getY() marked inline outside of the class body, after Y is complete.

In general, it may be preferable to define member functions in a
separate source file instead of in a header, if that member function
needs the complete definition of something and the declaration wouldn't.

The inline is to avoid multiple definitions if using the header in more
than one translation unit.

That is:

  struct Y;
  struct X
  {
    // ...
    Y getY() const;
  };

  struct Y
  {
    // ...
    X getX() const { return X(); }
  };

  inline Y X::getY() const { return Y(); }

-- 
Lars Viklund | zao_at_[hidden]

Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net