Reputation: 6200
Is C++ virtual definition recursive? Consider
class Foo
{
public:
virtual void a()=0;
};
class Bar:public Foo
{
public:
void a()
{
//...
}
};
If I now inherit Bar
and overload a
again, is that a
also polymorphic?
Recursive means that
Given a class
A
that has a virtual membera
, and a virtual member of then
:th subclass ofA
, thena
is also a virtual member of then+1
:th subclass, for alln
.
That is, virtual functions follow Peanos induction axiom and is not terminated after one level.
Upvotes: 4
Views: 130
Reputation: 117886
If you inherit from Bar
you should have
class Bar:public Foo
{
public:
virtual void a() override
{
//...
}
};
So you are saying two things about a()
here:
Bar
will treat the function as virtuala
from the base class Foo
As @MikeSeymour and @Bathsheba mentioned, the virtual
keyword in Bar
is superfluous as the function will be treated as virtual
since it was in the base class. However, I tend to be in the habit of using virtual
/override
as shown in my example so it is immediately clear how this function is to be used at first glance of the class without having to walk up the inheritance.
Upvotes: 4
Reputation: 234715
Any function with the (i) same name, (ii) the same parameter types, and (iii) a related return type in a base and child class that's marked virtual
in a base class will also be virtual in the child class.
So yes, void bar::a()
is virtual too. In fact, there is no way of removing the virtual
-ness in the child class function.
Your terms are imprecise. Overloading is concerned with having functions with the same name but different parameter types. Recursion is a control flow technique. Overriding is the re-implementation of a base class function in a child class.
Upvotes: 4
Reputation: 308206
In the normal case, an overridden virtual function is itself virtual. It doesn't matter whether the parent class function was virtual because you used the virtual
keyword or because it's own parent was virtual.
One thing to be careful of is when you "hide" one function with another of the same name but different signature. That function is not virtual!
class Foo
{
public:
virtual void a()=0;
};
class Bar:public Foo
{
public:
void a(); // virtual
};
class Baz1 : public Bar
{
public:
void a(); // also virtual
};
class Baz2 : public Bar
{
public:
void a(int); // not virtual!
};
Upvotes: 2
Reputation: 254471
"Recursive" isn't the right word; but yes, a function that overrides a virtual function is itself virtual.
Upvotes: 4