Lets say I have a class A, B and C
class A{
public:
virtual void f4(){
cerr<<"A::f4()"<<endl;
}
};
class B: public A{
public:
virtual void f4(int n){
cerr<<"B::f4("<<n<<")"<<endl;
}
};
class C: public B{
public:
virtual void f4(int n = 1){
cerr<<"C::f4("<<n<<")"<<endl;
}
};
If I have:
C c;
A& rac = c;
rac.f4();
I was expecting c's version of f4 to be called but that's not what happens. Can someone explain?
Compiling with clang -Wall the following warnings occur:
main.cpp:14:22: warning: 'B::f4' hides overloaded virtual function [-Woverloaded-virtual]
virtual void f4(int n){
^
main.cpp:6:22: note: hidden overloaded virtual function 'A::f4' declared here: different number of parameters (0 vs 1)
virtual void f4(){
^
These warnings explain what's going on. A virtual function is only overridden by another function with the same signature.
B::f4(int) does not override A::f4() because they have different parameter lists. Instead, it is a different virtual function.
So rac.f4() just calls A::f4() which is not overridden.
Since C++11 you can help to detect this problem:
virtual void f4(int n) override {
// ^^^^^^^^
Then the compiler will give an error if this function does not actually override something from the base.
Because the signatures of f4 don't match between A and B/C classes.
This is A's function signature for f4:
void A::f4() // no parameters
B and C use this function signature
void B::f4(int n)
If you are doing to override a method, it needs to have the same return type and identical parameter list. Otherwise, even if the method in the derived class has the same name as the parent class, C++ will don't consider that an override.
FWIW, C::f4 does override B::f4. The default parameter you introduce on class C doesn't influence the virtual methods override behavior. And this is the exact reason why, on my team, we disallow overloading methods with different signatures and banning default parameters. Because it leads to bugs like this.
Here's C's v-table (the methods available on it):
void C::f4(); // no parameters, overrides A::f4()
void C::f4(int n); // overrides B::f4()
Related
This question already has an answer here:
method in the derived class got executed without a *virtual* keyword in the referred class
(1 answer)
Closed 2 years ago.
Probably, i misunderstood c++ polymorphism(virtual function).
Please point me what i miss.
the source code is below
#include <iostream>
using namespace std;
class A {
public:
virtual void print(void) {
cout<<"class A"<<endl;
}
};
class B : public A {
public:
void print(void) {
cout<<"class B"<<endl;
}
};
class C : public B {
public:
void print(void) {
cout<<"class C"<<endl;
}
};
int main() {
A a;
B b;
C c;
A *pAa = &a;
A *pAb = &b;
A *pAc = &c;
B *pBc = &c;
pAa->print();
pAb->print();
pAc->print();
pBc->print(); // shouldn't be "class B"
return 0;
}
result
------------------------------
class A
class B
class C
class C // shouldn't be "class B"
my understanding is that
the last print statement should print "class B"
because pBc is a pointer of class B and the print function in class B is non virtual member function. i could not find the answer about this situation.
please tell me why or point me where i can find the answer and
understand c++ polymorphism in comprehension.
thanks.
If a function with a given signature is declared as virtual in a top-level base class, then the function is virtual in all derived classes no matter if it is marked with the keyword virtual (override, final) or not:
virtual function specifier
Then this function in the class Derived is also virtual (whether or not the keyword virtual is used in its declaration)
struct Base {
// Pure virtual function.
virtual void foo() const = 0;
};
struct A : public Base {
// Overriding virtual function, even if it
// is not marked as virtual (override, or final).
void foo() const {}
};
In A, adding the virtual specifier to foo() would only bring semantic value; it will be no functional difference whether virtual is omitted or not (unless someone changes the interface in Base).
Many static analyzers enforce(1) marking derived virtual functions with override or final, for two reasons:
semantics; clearly showing the given function is a virtual function (as per being defined so higher up in the inheritance chain), and
enforcement; if a function is marked as override and final but is not actually an overriding function, you will get a compiler error, which can be particularly useful to protect against mistakes when changing a base class interface (whilst forgetting which classes that actually implements this interface).
E.g.:
struct Base {
// Pure virtual function.
virtual void foo() const = 0;
};
struct A : public Base {
// Overriding virtual function.
void foo() const override {}
};
struct B final : public Base {
// Overriding (final) virtual function.
void foo() const final {}
// Error: Function does not override.
// void bar() const override {}
};
(1) E.g. Rule A10-3-1 in the Autsar C++14 Language Guidelines (safety-critical development in automotive) is categorized as a required rule: Virtual function declaration shall contain exactly one of the three specifiers:(1) virtual, (2) override, (3) final.
the print function in class B is non virtual member function
No. Since A::print is marked as virtual and B inherits from A, then B::print is virtual too; regardless of the keywork virtual is specified on it or not.
(emphasis mine)
If some member function vf is declared as virtual in a class Base, and
some class Derived, which is derived, directly or indirectly, from
Base, has a declaration for member function with the same
name
parameter type list (but not the return type)
cv-qualifiers
ref-qualifiers
Then this function in the class Derived is also virtual (whether or not the keyword virtual is used in its declaration) and overrides Base::vf (whether or not the word override is used in its declaration).
I have a class hierarchy that works approximately like this:
class A
{
protected:
virtual void f(int) = 0;
};
class B
{
protected:
virtual void f(char*) = 0;
};
class DA : A
{
private:
virtual void f(int) override {}
};
class DB : public DA, B
{
private:
virtual void f(char*) override {}
};
When I try to compile with clang (or gcc, for that matter), it gives me the warning
<source>:22:18: warning: 'DB::f' hides overloaded virtual function [-Woverloaded-virtual]
virtual void f(char*) override {}
^
<source>:16:18: note: hidden overloaded virtual function 'DA::f' declared here: type mismatch at 1st parameter ('int' vs 'char *')
virtual void f(int) override {}
^
Which I understand, but should it really give that warning? After all, DB cannot even see the hidden function (which might even be named the same by coincidence).
If it wasn't private, I could use
using DA::f;
to clarify, of course, but the function is private, DB doesn't even know about it, and certainly shouldn't expose it.
Is there a way to fix this without deactivating that warning, i.e. telling the compiler that everything is designed as is intended?
After all, DB cannot even see the hidden function (which might even be named the same by coincidence).
Accessibility and visibility are different concepts in C++. DA::f() is by default visible inside DB (and then hidden by DB::f()), but it is not accessible, because it is private inside DA, and DB is not a friend of DA. One could argue that hiding a function that is inaccessible is harmless, because it cannot be called anyway. However, the distinction between hidden and inaccessible can be significant because visible and inaccessible functions do participate in overload resolution. If db is an object of type DB, then what does db.f(0) do? If DA::f() is visible but inaccessible, it will be selected as best match and the compiler will emit a diagnostic because it is inaccessible and therefore cannot be called. If DA::f() is hidden, however, the compiler will select the overload that accepts a pointer instead, and treat the literal 0 as a null pointer.
What I ended up doing (for now) is using composition instead of private inheritance. So my code currently looks like
class A
{
protected:
virtual void f(int) = 0;
};
class B
{
protected:
virtual void f(char*) = 0;
};
class DA
{
class D : A
{
private:
virtual void f(int) override {}
} d;
};
class DB : public DA
{
class D : B
{
private:
virtual void f(char*) override {}
} d;
};
I'm not 100% happy with this, as the d members cause additional syntactial overhead, but at least it works without changing the public interface.
A possible way to fix the warning is to duplicate code of DA::f inside DB:
class DB : public DA, B
{
virtual void f(int i) override
{
// copy implementation of DA::f(int) as you cannot do
// return DA::f(i);
}
private:
virtual void f(char*) override {}
};
Demo
but a local pragma to remove warning seems more appropriate.
This has the feeling of a complete newbie question, but why does the following code not compile when the final specifier is used for B::operator()?
struct A
{
virtual void operator()() const = 0;
};
// the CRTP-component is not really necessary here
// but it possibly makes more sense in that it could be applied like this in reality
//
template<typename Derived>
struct B : A
{
virtual void operator()() const override final
{
static_cast<Derived const&>(*this).operator()();
}
};
struct C : B<C>
{
void operator()() const
{
//do something
}
};
int main()
{
C()();
}
G++ prints the following error message:
main.cpp:17:14: error: virtual function 'virtual void C::operator()() const'
void operator()() const
^
main.cpp:9:22: error: overriding final function 'void B<Derived>::operator()() const [with Derived = C]'
virtual void operator()() const override final
^
I would have thought it works as the non-virtual C::operator() does not override the virtual functions in its base classes? How can I bring this to work (--without changing the name of C::operator())?
EDIT: As pointed out by several users, the answer is simply that the virtual-keyword in the derived class is redundant (whereas I thought leaving it out would prevent from inheriting). However, the goal I had in asking this -- namely a consistent interface throughout the dynamic and static inheritance hierarchy -- can be solved by using a non-virtual operator[] throughout and couple classes A and B by a virtual function apply:
struct A
{
void operator()() const
{
this->apply();
}
protected:
virtual void apply() const = 0;
};
template<typename Derived>
struct B : A
{
void operator()() const
{
static_cast<Derived const&>(*this).operator()();
}
protected:
virtual void apply() const override final
{
this->operator()();
}
};
struct C : B<C>
{
void operator()() const
{
//do something
}
};
int main()
{
C()();
}
If a function is declared virtual in a base class, then a function declared with the same name and parameter list is implicitly virtual in derived classes, whether or not you use the virtual keyword. You cannot make C::operator()() non-virtual.
A function in a derived class with the same signature as a virtual function in a base class overrides that virtual function from the base class. That makes it a virtual function, even if/though the declaration in the derived class doesn't use the virtual key word.
That can't be changed, so if you really need to have a function with the same name in a derived class that doesn't override the virtual function from the base class (and in the process, become virtual itself and in this case, violate the final in B) you'll need to change the signature of the function in the derived class. That can mean a different name, different parameter list, or different qualifiers. I'd treat the latter two with extreme caution though--the compiler will be able to sort out the mess you've made, but many human readers may (very easily) be surprised.
If I were reviewing such code, I'd probably cite this as a problem, and the author would need to provide very solid reasoning for why it was truly necessary to get it approved.
As an override (because it has the same signature as the virtual function in a base class), the override conflicts with the final specified in its base class.
One fix (or rather workaround) is to give that function a defaulted argument, so that it has a different type and hence not an override, and a better approach is to fix the design.
Consider the next code :
#include <iostream>
using namespace std;
class A
{
public:
virtual int f() {cout <<"A:: f()\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.
Please consider the following code:
class Abase{};
class A1:public Abase{};
class A2:public A1{};
//etc
class Bbase{
public:
virtual void f(Abase* a);
virtual void f(A1* a);
virtual void f(A2* a);
};
class B1:public Bbase{
public:
void f(A1* a);
};
class B2:public Bbase{
public:
void f(A2* a);
};
int main(){
A1* a1=new A1();
A2* a2=new A2();
Bbase* b1=new B1();
Bbase* b2=new B2();
b1->f(a1); // calls B1::f(A1*), ok
b2->f(a2); // calls B2::f(A2*), ok
b2->f(a1); // calls Bbase::f(A1*), ok
b1->f(a2); // calls Bbase::f(A2*), no- want B1::f(A1*)!
}
I'm interested to know why C++ chooses to resolve the function call on the last line by upcasting the this pointer of the object to the base class, rather than upcasting the argument of f()? Is there any way that I can get the behaviour I want?
The choice of which version of f to call is made by looking at the compile-time type of the parameter. The run-time type isn't considered for this name resolution. Since b1 is of type Bbase*, all of Bbase's members are considered; the one that takes an A2* is the best match, so that's the one that gets called.
"...chooses to resolve the function call on the last line by upcasting the this pointer of the object to the base class...". What are you talking about? In all of your calls, the object pointer type is Bbase * and the functions the calls resolve to belong to either Bbase or its descendants. The compiler never does any upcasting in order to resolve your calls. In fact, the first two calls require downcasting in order to call the proper overrider, since the overrider belongs to the class located further down in the hierarchy. As for the last two calls - they are dispatched into the Bbase class through a pointer of Bbase * type. The types match exactly, no casting of any kind takes place.
As for the overload resolution... Overload resolution is a compile time process, which is based on the static types of the arguments and the ranks of possible conversions. You supplied an argument of A2 * type. The f(A2 *) candidate matched your argument precisely. The f(A1 *) candidate requires a extra conversion from A2 * to A1 *. The candidate that matches exactly is considered a better one, so it wins the overload resolution. Simple.
b1->f(static_cast<A1*>(a2));
This should force the compiler to use the overload method with parameter of type A1.
It's called name hiding. Every f you declare in one derived class shadows every possible f in any of its base classes.
Use a cast to the base class to get the desired behaviour.
When you override a virtual function, you don't override overloaded functions with the same name. They are different functions (and have different entries in the vtable).
Your overloads in Bbase for Abase and A2 are hidden in B1.
Maybe you can work around that problem like this:
class Bbase{
public:
inline void f(Abase* a) { f_(a); }
inline void f(A1* a) { f_(a); }
inline void f(A2* a) { f_(a); }
protected:
virtual void f_(Abase* a);
virtual void f_(A1* a);
virtual void f_(A2* a);
};
class B1:public Bbase{
protected:
void f_(A1* a);
};
class B2:public Bbase{
protected:
void f_(A2* a);
};
or with a template in Bbase:
class Bbase{
public:
template<class myA>
inline void f(myA* a) { f_(a); }
protected:
virtual void f_(Abase* a);
virtual void f_(A1* a);
virtual void f_(A2* a);
};