I have three different compilers that I am using to compile this code. One of them (the one that I trust the least) warns that the function in Derived hides the function in Base. The other compilers (one is Visual C++) does not warn. Visual C++ doesn't even give a warning about it if I enable /Wall or /W4.
I tend to believe that this is a bug in the compiler that's giving a warning, since it compiles the code. If it really didn't override the base function, then it should give an error when I create an instance of the derived template.
Can anyone confirm how this should behave?
struct Base
{
virtual void Func(float f) = 0;
};
template <typename T>
struct Derived : Base
{
virtual void Func(T f){}
};
int main()
{
Derived<float> d;
d.Func(0);
return 0;
}
When Derived
is instantiated with float
I get the unexpected warning. When Derived
is instantiated with int
I get an error, as expected.
To access the overridden function of the base class, we use the scope resolution operator :: . We can also access the overridden function by using a pointer of the base class to point to an object of the derived class and then calling the function from that pointer.
Functional Programming and Lambda- Learn Java8 by Coding itWhen the base class and derived class have member functions with exactly the same name, same return-type, and same arguments list, then it is said to be function overriding.
Which among the following best describes member function overriding? Explanation: The member function which is defined in base class and again in the derived class, is overridden by the definition given in the derived class.
It is indeed overridden. You can easily convince yourself in C++11 using the override
keyword, which won't allow code to compile if the function is not overridden:
struct Base
{
virtual void Func(float f) = 0;
virtual ~Base() = default; // to silence warnings
};
template <typename T>
struct Derived : Base
{
void Func(T f) override {} // will fail to compile if not overriding
};
int main()
{
Derived<float> d;
d.Func(0);
return 0;
}
Live example here.
Note that in pre C++11, you can accidentally hide a virtual
base function via changing its signature in a derived class, so even if you mark the derived function virtual
the code still compiles, but does is not polymorphic anymore, see such an example here. Unfortunately g++ doesn't provide any warnings, even with -Wall -Wextra
. That's why override
is a much safer way of actually enforcing true override at compile time.
I don't believe you should be given a warning.
This is the same as:
struct Derived : Base
{
virtual void Func(float f) { };
};
When your template parameter is float
.
There is no hiding, only implementation of an abstract function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With