Polymorphism in C ++ Why Doesn't It Work?

class Base {
    public:
    virtual void f();
    void f(int);
    virtual ~Base();
};

class Derived : public Base {
public:
    void f();
};

int main()
{
    Derived *ptr = new Derived;
    ptr->f(1);
    delete ptr;
    return 0;
}

ptr-> F (1); The following error appears: "too many arguments in the function call".

Why is this impossible? all functions of the form of the base are not inherited and can use any of them? I could call it explicitly, and it will work, but why is it not allowed?

+4
source share
4 answers

What you see is called hidden.

When you override a function void f()in a class Derived, you hide all other options for the function fin the class Base.

You can solve this with the keyword using:

class Derived : public Base {
public:
    using Base::f;  // Pull all `f` symbols from the base class into the scope of this class

    void f() override;  // Override the non-argument version
};
+11
source

@Some Programming Dude: - .

,

Inheritance Base / Derived.

1 : " "

f() Derived, Base .

, ,

void main()
    {
        Derived *ptr = new Derived;
        ptr->Base::f(1);
        delete ptr;
    }
+1

, Derived void Base::f(int);. function overloading. function overloading, f(int); , f(); Derived. function overloading . Function Overriding . , , -

0

"Derived * ptr" "ptr" -, Derived- . -, Derived - .

If you want to access the base class version of the function "f", use "Base * ptr" and it will automatically select the correct version of the function, as shown :)

class Base {
    public:
        virtual void f()
        {
            cout<<"Here 2"<<endl;
        }
        void f(int x)
        {
            cout<<"Here 1"<<endl;
        }
        virtual    ~Base() {}
};

class Derived : public Base {
    public:
        void f()
        {
            cout<<"Here 3"<<endl;
        }
        virtual   ~Derived() {}
};

int main()
{
    Base *ptr = new Derived;
    ptr->f(1);
    delete ptr;
    return 0;
}

conclusion here 1

-1
source

Source: https://habr.com/ru/post/1666227/


All Articles