Pointers And References To The Base Class Of Derived Objects

Consider the following program:

#include <iostream>
 
using namespace std;
 
class Base
{
        protected:
                int m_nValue;
        public:
                Base(int nValue) : m_nValue(nValue)
                {}
                const char* GetName() { return "Base";}
                int GetValue() { return m_nValue; }
};
 
class Derived: public Base
{
        public:
                Derived(int nValue) : Base(nValue) {}
                const char* GetName() { return "Derived"; }
                int GetValueDoubled() { return m_nValue*2; }
};
 
int main()
{
        Derived cDerived(5);
        cout << "cDerived is a " << cDerived.GetName() << " and has value "
        << cDerived.GetValue() << endl;
 
        Derived &rDerived = cDerived;
        cout << "rDerived is a " << rDerived.GetName() << " and has value "
        << rDerived.GetValue() << endl;
        Derived *pDerived = &cDerived;
         cout << "pDerived is a " << pDerived->GetName() << " and has value "
        << pDerived->GetValue() << endl;
 
        Base &rBase = cDerived;
        Base *pBase = &cDerived;
 
        cout << "rBase is a " << rBase.GetName() << " and has value " << rBase.GetValue() << endl;
        cout << "pBase is a " << pBase->GetName() << " and has value " << pBase->GetValue() << endl;
 
        return 0;
}

This will print:
cDerived is a Derived and has value 5
rDerived is a Derived and has value 5
pDerived is a Derived and has value 5
rBase is a Base and has value 5
pBase is a Base and has value 5

So the pointer pBase doesn't know that is pointing to a Derived object. The solution is virtual functions

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-Share Alike 2.5 License.