passing a derived class object to constructor of template class
<p>Hi everybody out there!</p>

<p>My question is as follows:</p>

<p>I have a template class which stores pointer to a method of other classes (of course the template class is unaware initially of the types of classes to be passed to it).
I made the constructor of the template class to take a pointer to the passed in class, and another argument which is the address of the method of the passed in class that I want to store, as follows:</p>

<pre><code>    template &lt;typename MyClass&gt;
    TemplateClass
    {
    typedef void (MyClass::*MethodPointer)();
    MyClass* theClass;
    MethodPointer methodPointer;
public:
    TemplateClass(MyClass* cl, MethodPointer func) : theClass(cl), methodPointer(func){}

    void Excute()
    {
        return (theClass-&gt;*methodPointer)();
    }
    };
</code></pre>

<p>Then, I made a base class, and derived a subclass from it.</p>

<pre><code>    class BaseClass
    {
        // other details are omitted...
        virtual void DoSomething();
    };

    class DerivedClass : public BaseClass
    {
        // other details are omitted...
        void DoSomething();
    };

    // the definitions of the methods is omitted because it had no relevance to the issue
</code></pre>

<p>Then, I made a typedef of the template class taking the base class as the parameter such as:</p>

<pre><code>    typedef TemplateClass&lt;BaseClass&gt; TypedTemplateClass;
</code></pre>

<p>Then, when I try to pass a pointer of the derived class to the constructor of TypedTemplateClass, the compiler says that it cannot convert the argument from the derived class to the base class, as follows:</p>

<pre><code>    DerivedClass* myDerivedObject = new DerivedClass();
    TypedTemplateClass* myTemplateObject = new TypedTemplateClass(myDerivedObject, &amp;DerivedClass::DoSomething);
</code></pre>

<p>But if I pass an object of the base class itself, everything works well! Just as follows:</p>

<pre><code>    BaseClass* baseObject = new BaseClass();
    TypedTemplateClass* myTemplateObject2 = new TypedTemplateClass(baseObject, &amp;BaseClass::DoSomething);
</code></pre>

<p>So, Can somebody enlighten me to get over this problem?
I am aware that the problem lies in that the typed template class is expecting a base class object, but I need to pass the derived class object - because I intend to make different derived classes and be able to pass their methods polymorphically to the template class.
I am also aware that I could just ignore the TypedTemplateClass definition and just create template class objects each with a different derived class type. However, the above proposal is my intention.</p>

<p>I am using visual studio IDE</p>

<p>Thanks in advance for your interest and kind help.</p>
