nicolas.hilaire@motorola.com wrote:[color=blue]
> trying to implement a factory, i try :[/color]
Next time, quote the message you are answering to, like I do in this
post.
[color=blue]
> class A
> {
> public:
> virtual void DoSomething();[/color]
A virtual function *must* be implemented. That's why you are receiving
a linker error.
virtual void DoSomething()
{
}
"But this DoSomething() has nothing to do!" That's right, so make it
*pure* virtual.
virtual void DoSomething() = 0;
That way
1) the function is virtual (may be overrided by derived classes and
correctly called using a pointer to base class)
2) the function has no implementation
a) making the class "abstract" (may not be instantiated)
b) forcing the derived classes to implement the function
Also, if you intend to delete derived objects from a base pointer:
void f(Base *b)
{
delete b;
}
int main()
{
Derived *d = new Derived;
f(d);
}
you *must* make the destructor virtual or you'll get undefined behavior
(very probably, the wrong destructor will be called and memory may be
leaked).
class Base
{
public:
virtual ~Base() {}
};
[color=blue]
> };
>
> class B : public A
> {
> public:
> B() { cout << "Constructor of B" << endl; }
> void DoSomething() { cout << "Do something from B" << endl; }
> };
>
> class C : public A
> {
> public:
> C() { cout << "Constructor of C" << endl; }
> void DoSomething() { cout << "Do something from C" << endl; }
> };
>
> class Factory
> {
> public:
> A* Create(int i)
> {
> if (i)
> return new B();
> else
> return new C();
> }[/color]
Well, that's a very good starting point.
The problem here is that Factory is a "dependency bottleneck". That
means Factory needs to know about all the possible classes it can
create. It would be better better if the classes themselves could
register to the factory. But that's an "advanced" subject so I suggest
you begin with your Factory class. Someday, you'll realize that not
only is it complicated to add new classes to your hierarchy, but it
takes a while to recompile your program everytime you make a single
change to one header. When that time arrives, look for the references I
gave you.
[color=blue]
> };
>
> int main(int argc, char* argv[])
> {
> Factory myFactory;
> A * a = myFactory.Create(0);
> a->DoSomething();
> return 0;
> }
>
>
> but this gives me an error : error LNK2001: unresolved external symbol
> "public: virtual void __thiscall A::DoSomething(void)"
> (?DoSomething@A@@UAEXXZ)
>
> How should i do ??[/color]
This should be solved by either implementing the virtual function or
(more probably) by making it pure virtual (with the =0 thing at the
end).
Jonathan