Factory method in Interface

Jan 27, 2011 at 9:18am
Hi,

I have an abstract class which defines an interface for an object.
Now I need a factory method to create object.

IMyObj.h
1
2
3
4
5
public class IMyObj
{
  virtual int Method1() = 0;
  static IMyObj* CreateMyObj();
}


CMyObj.h
1
2
3
4
5
6
7
#include "IMyObj.h"

public class CMyObj : public IMyObj
{
  int Method1();
  static IMyObj* CreateMyObj();
}


CMyObj.cpp
1
2
3
4
5
6
7
#include "CMyObj.h"

int CMyObj::Method1() 
{ ... }

IMyObj* CreateMyObj() 
{ return new MyObj(); }


When I use the code in a test project I receive "unresolved external symbol" on IMyObj::CreateMyObj

1
2
3
#include "IMyObj.h"

IMyObj* pMyObj = IMyObj::CreateMyObj();


Where I wrong?

Regards,
Daniele.
Jan 27, 2011 at 9:33am
Your syntax is incorrect.

IMyObj.j should have:
1
2
3
4
5
6
class IMyObj
{
public:
  virtual int Method1() = 0;
  static IMyObj* CreateMyObj();
};

... and so on.
Jan 27, 2011 at 9:44am
Yes, sorry...I forgot the 'public' keywork in the example...but, of course, in my code I put it!
Daniele.
Jan 27, 2011 at 10:14am
It all depends on where you want the creator to go. But let's assume that you want one in each concrete class and not the interface, then CMyObj.cpp should be:
1
2
3
4
5
6
7
#include "CMyObj.h"

int CMyObj::Method1() 
{ ... }

IMyObj* CMyObj::CreateMyObj() 
{ return new MyObj(); }


IMyObj.h should have:
1
2
3
4
5
class IMyObj
{
public:
  virtual int Method1() = 0;
};


And CMyObj.h remains unchanged.
Last edited on Jan 27, 2011 at 10:17am
Topic archived. No new replies allowed.