Search code examples
c++classinheritanceradix

Expected result not working when inheriting?


EDIT!

Stupid typo of which I didn't see caused this problem. Solved now. Thankyou everyone!

Why wont my code output the cout's from each individual class?

Expected result should be Message from 1 and Message from 2?

class CTest
{
public:
    virtual void WriteMessage();
};
void CTest::WriteMessage()
{
}

class CMessage1 : public CTest
{
    virtual void WriteMesssage()
    {
        cout << "Message from 1" << endl;
    }
};


class CMessage2 : public CTest
{
    virtual void WriteMesssage()
    {
        cout << "Message from 2" << endl;
    }
};


int _tmain(int argc, _TCHAR* argv[])
{

    CTest* pMessages[4];
    pMessages[0] = new CMessage1;
    pMessages[1] = new CMessage2;
    pMessages[2] = new CMessage1;
    pMessages[3] = new CMessage2;
    for (int i = 0; i < 4; i++)
    {
        pMessages[i]->WriteMessage();
    }
    return 0;
}

Do I need to create the WriteMessage virtual void for each instance of CMessage? Like this:

void CMessage2::WriteMesssage()
{
cout << "Message from 2" << endl;
}

Solution

  • You misspelled WriteMessage as WriteMesssage (note the 3 's'), thus it does not override the base version.

    Note that using the override keyword (from of C++11) can help tell you when you're not overriding what you intended to.