简体   繁体   中英

overloading in inheritance c++

so I got this problem while trying to overload in c++: I have those classes:

class Data
{
public:
    void virtual f(){cout<<"In data!"<<endl;}
};

class A: public Data
{
public:
    void f(int x){cout<<"Class A int is: "<<x<<endl;}

};

then I do:

Data *D=new A();
D->f(4);

I expect the Data's f() function to do to class A's f() function since I did it virtual, but it won't.

Any ways to make it work?

That's not the same function, the one in the derived class takes an int parameter.

That shouldn't even compile, because Data doesn't have a method called f(int) .

For polymorphism to work, you need the same signature:

class Data
{
public:
    void virtual f(int){cout<<"In data!"<<endl;}
    //              |
    //        dummy parameter
};

class A: public Data
{
public:
    void f(int x){cout<<"Class A int is: "<<x<<endl;}
};

You need to have the same parameters when overloading. Your compiler sees doStuff(int a), doStuff(String a) and doStuff() as different functions. Be sure they all have the same parameters when you're overloading.

Overloading does not work across class boundaries. Here is something you can do to be able to call both using an object of class A -

class Data
{
public:
    void virtual f(){cout<<"In data!"<<endl;}
    //              |
    //        dummy parameter
};

class A: public Data
{
    using Data::f;

public:
    void f(int x){cout<<"Class A int is: "<<x<<endl;}
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM