Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does a virtual function get hidden?

Tags:

I have the following classes:

class A { public:     virtual void f() {} };   class B : public A{ public:     void f(int x) {} }; 

If I say

B *b = new B(); b->f(); 

the compiler says error C2660: 'B::f' : function does not take 0 arguments. Shouldn't the function in B overload it, since it is a virtual function? Do virtual functions get hidden like this?

EDIT: I indeed meant to inherit B from A, which shows the same behaviour.

like image 767
Oszkar Avatar asked Nov 10 '10 16:11

Oszkar


People also ask

Do virtual functions have to be public?

Virtual functions, in their view, should never be public, because they define the class' interface, which must remain consistent in all derived classes. Protected and private virtuals define the class' customizable behavior, and there is no need to make them public.

Can a virtual function be private?

A virtual function can be private as C++ has access control, but not visibility control. As mentioned virtual functions can be overridden by the derived class but under all circumstances will only be called within the base class.

Why are virtual functions set 0?

It's just a syntax, nothing more than that for saying that “the function is pure virtual”. A pure virtual function is a virtual function in C++ for which we need not to write any function definition and only we have to declare it. It is declared by assigning 0 in declaration.

What happens when a virtual function is called?

A virtual function is a member function that you expect to be redefined in derived classes. When you refer to a derived class object using a pointer or a reference to the base class, you can call a virtual function for that object and execute the derived class's version of the function.


1 Answers

Assuming you intended B to derive from A:

f(int) and f() are different signatures, hence different functions.

You can override a virtual function with a function that has a compatible signature, which means either an identical signature, or one in which the return type is "more specific" (this is covariance).

Otherwise, your derived class function hides the virtual function, just like any other case where a derived class declares functions with the same name as base class functions. You can put using A::f; in class B to unhide the name

Alternatively you can call it as (static_cast<A*>(b))->f();, or as b->A::f();. The difference is that if B actually does override f(), then the former calls the override, whereas the latter calls the function in A regardless.

like image 147
Steve Jessop Avatar answered Sep 22 '22 09:09

Steve Jessop