-4
    #include<iostream>

    class CBase
    {
    public:
            virtual        void PrintData(int nData = 111);
    };
    void CBase::PrintData(int nData /* = 111 */)
    {
            printf("CBase::PrintData, nData = %d\n", nData);
    }

    class CDerived : public CBase
    {
    public:
            void PrintData(int nData = 222);
    };
    void CDerived::PrintData(int nData /* = 222 */)
    {
            printf("CDerived::PrintData, nData = %d\n", nData);
    }

    int main()
    {
            CDerived oCDerived;
            CBase* pCBase = &oCDerived;

            pCBase->PrintData();
            (*pCBase).PrintData();
            oCDerived.PrintData();
            return 0;
    }





run and print:
  CDerived::PrintData,nData = 111
  CDerived::PrintData,nData = 111
  CDerived::PrintData, nData = 222

I am sorry that I made a typo because I wanna use my own code to test. There is the code what I am confused with. As expected,pCBase is a pointer to the base subject of derived class object oCDerived,so calling PrintData() through pCBase pointer equals to calling PrintData() override by Derived class object.It should printf 222 222 and 222 by turns.

  • 1
    You have `print()` declared in the base class, but all of your derived class functions have functions named `prinf()`. Is this the actual code, or is that a typo? And if it's a typo, why are you typing in the code instead of copying / pasting the exact code from your code editor? – PaulMcKenzie Dec 19 '17 at 04:35
  • Possibly this will helps : https://stackoverflow.com/questions/5273144/c-polymorphism-and-default-argument – Nikita Smirnov Dec 19 '17 at 06:20
  • The default argument is obtained based on the type of pointer used to call the method, not the polymorphic type, as explained in the linked duplicate. Bear in mind that the derived type may be "hidden" (e.g. through some factory machinery), so the compiler would not be able to "see" the default argument of the derived type. – Niall Dec 19 '17 at 06:36

1 Answers1

2

When overriding a method, add they contextual keyword override after the argument list like this:

    void prinf()override{cout<<"bbb"<<endl;}

if you do so, you'll get an error when the base class has print while you have a typo in derived that says prinf.

This also explains your symptoms.

Rename prinf to print everywhere in your code.

Yakk - Adam Nevraumont
  • 262,606
  • 27
  • 330
  • 524