Factory method in Interface

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.
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.
Yes, sorry...I forgot the 'public' keywork in the example...but, of course, in my code I put it!
Daniele.
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
Topic archived. No new replies allowed.