Smart Pointers with Abstract Factory

Joined
Dec 12, 2008
Messages
1
Reaction score
0
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
 

Ask a Question

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

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,009
Latest member
GidgetGamb

Latest Threads

Top