Smart Pointers with Abstract Factory

Discussion in 'C Programming' started by muswei, Dec 12, 2008.

  1. muswei

    muswei

    Joined:
    Dec 12, 2008
    Messages:
    1
    I am trying to create abstract factory function to create smart pointers of different derived classes that have the same base class. One of the derived classes has an extra function that is not in the base or the other derived class. If I try to call that extra function "WhoAmI" the code will not compile. Any idea what is wrong here? Do I need to cast my auto_ptr from Base to DerivedB? Is this the proper way of doing this? In the end I just want some code that will create different derived classes based on certain criteria that do not leak memory.

    Here is my full code that I am trying to get to work.

    Code:
    #include <iostream>
    #include <fstream>
    
    #include <string>
    
    #include <stdio.h>
    #include <sstream>
    #include <stdlib.h>
    #include <sstream>
    #include <memory>
    
    
    
    using namespace std;
    class Base
    {
    public:
    	virtual void PrintMe() = 0;
    };
    
    class DeriveA : virtual public Base
    {
    public:
    	void PrintMe()
    	{
    		std::cout << "I am DeriveA\n";
    	}
    };
    
    class DeriveB : virtual public Base
    {
    public:
    	void PrintMe()
    	{
    		std::cout << "I am DeriveB\n";
    	}
    
    	void WhoAmI()
    	{
    		std::cout << "I think I am DeriveB\n";
    	}
    };
    
    std::auto_ptr<Base> CreateIt(std::string t)
    {
    	if(t == "A")
    	{
    		std::auto_ptr<Base> p(new DeriveA()); 
    		return p;
    	}
    
    	if(t == "B")
    	{
    		std::auto_ptr<Base> p(new DeriveB());
    		return p;
    	}
    }
    
    int main(int argc, char* argv[])
    {
    	std::auto_ptr<Base> p = CreateIt("A");
    	p->PrintMe();
    
    	std::auto_ptr<Base> c = CreateIt("B");
    	c->PrintMe();
    	c->WhoAmI();
    
    	return 0;
    }
    Thanks
     
    muswei, Dec 12, 2008
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Medi Montaseri
    Replies:
    17
    Views:
    897
    Medi Montaseri
    Sep 3, 2003
  2. MotoK
    Replies:
    59
    Views:
    1,852
    Keith Thompson
    Sep 15, 2006
  3. n2xssvv g02gfr12930

    Smart pointers and member function pointers

    n2xssvv g02gfr12930, Nov 26, 2005, in forum: C++
    Replies:
    3
    Views:
    481
    n2xssvv g02gfr12930
    Nov 27, 2005
  4. Steven T. Hatton
    Replies:
    7
    Views:
    392
    Kai-Uwe Bux
    Nov 30, 2006
  5. C#
    Replies:
    4
    Views:
    421
Loading...

Share This Page