I'm attempting to implement the Factory Pattern. I have a class called "Window" which has a class member function which determines which object is being called and then assigns the particular object pointer. I have written the following code:

class Hamming  {

public:

    Hamming() { }
    Hamming(int theSize) {

        // code 
    } 
};

class Window {

public:

    Window() { }
    Window* createInstanceOf(int theWindow, size_t size) {

        Window* w;

        w = new Hamming(100);

                   return w;
    }
};

I want to be able to call it from the following:

Window* w;
w->createInstanceOf(val, val2);

I get the following error:

error: assigning to 'Window *' from incompatible type 'Hamming *'
                    w = new Hamming(100);

The problem is, I don't really want to use inheritance or have to include every class inside of the implementation of this class (if i had a .h and .cpp file) because this requires EVERY class to be compiled, and, if I only need to use one instance "Hamming" then I don't need to include the others.

Any suggestions?

Covariance only works within an inheritance hierarchy. What you seem to want is a variant type in general, which can be achieved using Boost::Any or Boost::Variant, depending on your needs.

That said, what exactly are the criteria for selecting the type in your factory? This can change how feasible a solution is without relying on external libraries.

Yes - It looks like I'm going to have to have a inheritance hierarchy for this to work.

I need to do this because there exists multiple Windowing Functions, I need to be able to access the w pointer in another class and this method seems to be the only solution around it.

Thank you for the help :)

However,

When I have the following:

Window.cpp

Window* Window::Window::createInstanceOf(int theWindow, size_t size) {

        Window::Window* w;

        w = new Hamming(size);

        w = new Hanning(size);
}

I have to include the following files:

Hamming.h, Hanning.h

And at compile time, I have to link both of these .cpp files.. BUT what if I was just using Hamming.h and calling it like:

Hamming* h = new Hamming(100);

Is there a way around this?

Are you asking if there's a way to avoid linking with the implementation of a class? If so, that's like asking if you can buy a car without an engine and be able to drive it around normally. ;)

Noo.. Like having 10 cars to go into work.. You decide one morning to drive the 4x4 but it means that you have to take the sports car with you as well.. But, you don't need the sports car.. Make sense? :P

I think I've found a way around it, just include the implementation from the sub-classes inside the .h

But, you don't need the sports car.. Make sense? :P

That's where the analogy breaks down, because you do need the classes. If you didn't need them, you wouldn't be using them in the code, right?

This article has been dead for over six months. Start a new discussion instead.