开发者

Virtual method causes compilation error in Derived class

开发者 https://www.devze.com 2023-04-02 08:32 出处:网络
Consider the next code : #include <iostream> using namespace std; class A { public: virtual int f() {cout <<\"A:: 开发者_如何学Cf()\\n\"; return 1;}

Consider the next code :

#include <iostream>
using namespace std;

class A
{
public:
    virtual int f() {cout <<"A:: 开发者_如何学Cf()\n"; return 1;}
    virtual void f(int) {cout <<"A:: f(int)\n";}
    virtual void g() {cout <<"A::g()\n";}
};

class B3 : public A
{
public:
    void f() {cout <<"B3::f ()\n";}
};

int main()
{
    return 0;
}

It produces the following error :

..\main.cpp:17: error: conflicting return type specified for 'virtual void B3::f()'
..\main.cpp:9: error:   overriding 'virtual int A::f()'

but why ? in the worst case I'd think I'd have an Hiding case , but instead I get compilation error regarding A's virtual int f() {cout <<"A:: f()\n"; return 1;}

thanks ,Ronen


Don't confuse overriding with hiding. You override virtuals.

Your class definition is equivalent to:

class B3 : public A
{
public:
    virtual void f() {cout <<"B3::f ()\n";}
};

Once a function declared virtual, it will remain virtual for all classes deriving from your base class, regardless of whether you explicitly declare it virtual or not. Therefore you are trying to override a virtual function and changing its return type, which is illegal in C++. If the function were not virtual, you would simply be hiding the base class implementation, therefore changing the return type is valid. There would be no ambiguity since the compiler would know where to call the function from and what return type to expect.

However, consider having:

A* a;
....
a->f();

What would a-f() return? a is a pointer to A, but can point to an object of type B3. So it either returns an int or doesn't return anything. See the ambiguity here?

Instead, no polymorphism involved,

A a;
a.f();

will cal f from a, same as b3.f would call f from B3. All in all, overriding base class functions implies keeping the same return type. If you want to create a new function with a different return type, change its signature (either its name or its parameters - or both).

Anyway, you shouldn't even be doing this... Why would you want to have a function with the same name and no parameters return different things? Wouldn't adding a separate function be more readable?


You'd have hiding if f() would have had a different parameter list, or not declared as virtual on the base class. In the former case, since overloading doesn't cross inheritance borders, A's f would have been hidden. But this is not the case, since you have f() on both classes, which only differ in return value. Return values covariance is the only difference allowed, and since it's not the case (void does not inherit from int), you get the error.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号