Overloading a virtual function in a child class

前端 未结 6 1702
一向
一向 2021-01-08 01:04

I am just testing with virtual keyword and inheritance concepts in c++. I have written a small program:

#include
#include

us         


        
6条回答
  •  孤独总比滥情好
    2021-01-08 01:23

    It's because the print function in the child class takes a parameter and the original doesn't.

    in cna_MO (parent class):

    virtual void print()
    

    in cna_bsc (child class):

    void print(int a)
    

    Basically the child's print should not take an int argument:

    void print()
    

    EDIT:

    Maybe the best would be to make passing the int optional ?

    eg:

    in cna_MO (parent class):

    virtual void print(int a=-1) {
        if (a == -1) {
            // Do something for default param
        } else {
            cout << a;
        }
    }
    

    in cna_bsc (child class):

    void print(int a=-1)
    

    so if a == -1 you can probably assume, they didn't pass anything.

    The trick is that both the parent and child need the same method siganture, meaning same return type and the same argument types.

提交回复
热议问题