Home > Blockchain >  Why does Child Class shaddow Parent methods even though parameters are of different type
Why does Child Class shaddow Parent methods even though parameters are of different type

Time:10-23

My parent class holds two functions: On is supposed to be overwritten by the child, the second (same name) just uses as input a different type and than uses the overwritten method. Now I understand that if I define in the child class a method with the same name and same input parameters, it will shadow (is that the right expression?) the parents method. But I can still call the parents method by calling it explicit like: b.A::getSize(...).

My question is: Why does the parent method get shadowed even if the input parameter types are different? Why can't the compiler find the parent method with the correct input types? See the below minimal example.

And bonus question: Is it possible to achieve the behaviour that I can call the parents method without the need of the explicit call and without modifying main(){...} nor class B{...}; nor using different names?

#include <cstdio>

class A{
    public:
    virtual void getSize(size_t &i) = 0;

    void getSize(int &d){
        size_t i;
        getSize(i);
        d = static_cast<int>(i);
    }
};

class B : public A{
    public:
    using A::getSize; // This was in my case an acceptable solution thx @Mansoor/@user2357112
    void getSize(size_t &i) override{
        i = 4;
    }
};

int main(){
    size_t t;
    int i;
    B b;
    b.getSize(t);
    b.getSize(i); // error: non-const lvalue reference to type 'size_t' (aka 'unsigned long') cannot bind to a value of unrelated type 'int'
    b.A::getSize(i); // this works but is not acceptable (too much changes in production code)
    printf("%zu, %d",t,i);
    return 0;
}

CodePudding user response:

You can choose to expose the method with a using statement:

class B : public A
{
    // ...
    using A::getSize;
}

In your code snippets, you have used initialised values in many places, this invokes UB.

  • Related