Click here to Skip to main content
12,451,860 members (67,740 online)
Click here to Skip to main content

Tagged as

Stats

9.1K views
50 downloads
4 bookmarked
Posted

shared_ptr and the class factory

, 9 Aug 2012 CPOL
shared_ptr and the class factory
// Code generated and tested with VS2010
#include <memory>
#include <iostream>

using namespace std::tr1;
using namespace std;

class base
{
public:
   virtual ~base() {}
   virtual void hi() { std::cout << "Hi from base\n"; }
};

class derrivedTrue : public base
{
public:
   virtual ~derrivedTrue(){}
   virtual void hi() { std::cout << "Hi from derrivedTrue\n"; }
   void hello() {std::cout << "Hello derrivedTrue\n"; }
};

class derrivedFalse : public base
{
public:
   virtual ~derrivedFalse(){}
   virtual void hi() { std::cout << "Hi from derrivedFalse\n"; }
   void hello() {std::cout << "Hello derrivedFalse\n"; }
};

shared_ptr<base> factory(bool whichType)
{
   if(whichType)
      return make_shared<derrivedTrue>();
   else
      return make_shared<derrivedFalse>();
}

template<typename T>
class PDerrived
{
public:
   PDerrived( shared_ptr<base> p_ )
      : b(p_)
      , pd( dynamic_cast<T *>(p_.get()) )
   {
      cout << "ctor\n";
   }

   T *operator->() const {return pd; }
   operator bool () const { return pd != nullptr; }
   operator shared_ptr<base> () const { return b; }

private:
   shared_ptr<base>  b;
   T *pd;
};

int main(void)
{
   PDerrived<derrivedTrue> b = factory(true);
   if( b )
   {
      b->hi();
      b->hello();
   }

   PDerrived<base> b2 = b;
   if( b2 )
      b2->hi();

   PDerrived<derrivedFalse> c = factory(false);
   if( c )
   {
      c->hi();
      c->hello();
   }

   PDerrived<base> d = factory(true);
   if( d )
      d->hi();

   PDerrived<derrivedFalse> e = factory(true);
   if( e )
      e->hi();
   else
      cout << "Oops mismatch PDerrived with returned type\n";

   return 0;
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

mzdude
United States United States
No Biography provided

You may also be interested in...

Pro
Pro
| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.160826.1 | Last Updated 9 Aug 2012
Article Copyright 2012 by mzdude
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid