auto_ptr with Abstract Factory

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#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
You cannot access the functions of derived classes through the base class pointer if they are not virtual base class functions (without casting, that is. And when casting make sure not to use C-style casts, they don't mix with virtual inheritance (which you don't seem to require here, anyways.)
Last edited on
Topic archived. No new replies allowed.