Jack Tuyp
Jack Tuyp

Reputation: 3

boost::shared_ptr - composition relation between two classes

Suppose that I have:

To implement this, in C++ I:

A code example is given below.

    #include "boost/scoped_ptr.hpp"

    class C
    {
      public:
        C() {}

      private:

    };

    class P
    {
      public:
        P() : childC(new C()) {}

      private:
        boost::shared_ptr<C> childC;
    };

    int main(int argc, char** argv)
    {
        P p;
    }

Somehow I can't build this simple code example, and I don't get why (I'm a novice to programming).

Errors:

class ‘P’ does not have any field named ‘childC’

expected ‘;’ before ‘<’ token

invalid use of ‘::’

ISO C++ forbids declaration of ‘shared_ptr’ with no type

Upvotes: 0

Views: 732

Answers (2)

juanchopanza
juanchopanza

Reputation: 227410

The most likely cause of your errors is that you are including boost/scoped_ptr.hpp and you are trying to declare a boost::shared_ptr. It is unlikely you need a boost::shared_ptr here.

The simplest way to express composition in this case would be

class C {};
class P 
{
 private:
  C c_;
};

Now you may want to reduce compile time dependencies by using an idiom that requires only a forward declaration of C, in which case P's header could be

#include <boost/scoped_ptr.hpp>

class C; // forward declaration

class P
{
 public:
  P() : c_(new C()) {}
 private:
  boost::scoped_ptr<C> c_;
};

Upvotes: 3

thiton
thiton

Reputation: 36049

As KerrekSB has hinted in the comments, you have used shared_ptr, but included scoped_ptr. The difference is that the scoped_ptr expresses exclusive ownership (which is the case here), while shared_ptr expresses shared ownership (which is not the case). The preferred idiom is to use scoped_ptr in the code.

If you absolutely want to use shared_ptr, include the header <boost/smart_ptr/shared_ptr.hpp>.

Upvotes: 0

Related Questions