Search code examples
c++boostshared-ptr

boost::shared_ptr - composition relation between two classes


Suppose that I have:

  • two classes: P and C.
  • composition relations between P <>- C, i.e. every instance of P contains an instance of C, which is destroyed when the parent P instance is destroyed.

To implement this, in C++ I:

  • define two classes P and C;
  • define a member variables of P of type boost::shared_ptr, and initialize it with a newly created object in P's constructor.

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


Solution

  • 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_;
    };