Search code examples
c++templatesdynamic-cast

Calling a Derived Class Object's Method inside a Template [Using dynamic_cast]


so i'm trying to call a derived class object method using the dynamic_cast

    template<class T>
void stack<T>::objOps()
{
    T* a = this->arr[top];
    char s; 
    Gorilla* TempGorill = dynamic_cast<Gorilla*>(a);
    cout << "Select Object Functions: " << endl << endl
         << "<R>oar" << endl;
    if (TempGorill) { cout << "Chest<B>eating" << endl; }
    else { cout << "<M>akeFire" << endl << endl; }
    cout << "Your Choice-> ";   cin>>(s);
    switch(s)
    {
    case 'R': case 'r': a->roaR();
        if( TempGorill) 
        { case 'B': case 'b': a->chestBeating(); }
        else { case 'M': case 'm': a->makeFire(); }
    }


} 

roaR is all good becasue its a pure virtual in monkey , but chestBeating is exclusivley in Goriila and makeFire in chimp, they are both derived classes of monkey. the weird thing is that it DOES prints the right methods depending i choose either Gorilla or chimp, but cannot access to their methods errors i get:

    >c:\users\eizzy\documents\visual studio 2010\projects\copiedproject\copiedproject\newstack.h(135): error C2039: 'chestBeating' : is not a member of 'monkey'
    1>          c:\users\eizzy\documents\visual studio 2010\projects\copiedproject\copiedproject\monkey.h(8) : see declaration of 'monkey'
    1>          c:\users\eizzy\documents\visual studio 2010\projects\copiedproject\copiedproject\newstack.h(122) : while compiling class template member function 'void stack<T>::objOps(void)'
c:\users\eizzy\documents\visual studio 2010\projects\copiedproject\copiedproject\newstack.h(136): error C2039: 'makeFire' : is not a member of 'monkey'
1>          c:\users\eizzy\documents\visual studio 2010\projects\copiedproject\copiedproject\monkey.h(8) : see declaration of 'monkey'

thanks for the help.


Solution

  • In your switch scope, Shouldn't you be doing 'TempGorill->chestBeating()' ?