Difference between redefining and overriding a function
Asked Answered
C

2

26

Suppose I have class A with a virtual function F():

class A
{
    virtual void F()
    {
        // Do something
    };
};

And I have another class B which inherits A and redefines F():

class B : A
{
    void F()
    {
        // Do something
    };
};

And a different class C which also inherits A but overrides F():

class C : A
{
    void F() override
    {
        // Do something
    };
};

What is the difference between F() in classes B and C?

Crescin answered 19/2, 2016 at 13:45 Comment(0)
V
24

Both B::f() and C::f() are overrides and they are exactly the same.

override is essentially a compile-time advisory term that will cause a compilation error if the function does not override one in a base class.

This can help program stability: if the name and parameter types to A::f() are changed, then a compile error will result.

Virgulate answered 19/2, 2016 at 13:50 Comment(0)
H
29

Both are overrides.

When you use the keyword override you ensure a compilation failure if it should happen to not be an override.

And that's good practice.

Hara answered 19/2, 2016 at 13:46 Comment(2)
Not to mention the readability factor when perusing repositories like gitAltigraph
@Tgsmith61591: Yes. I also wondered whether to include an example of how to overload (essentially "redefine") without overriding. But I decided to be concise. :)Hara
V
24

Both B::f() and C::f() are overrides and they are exactly the same.

override is essentially a compile-time advisory term that will cause a compilation error if the function does not override one in a base class.

This can help program stability: if the name and parameter types to A::f() are changed, then a compile error will result.

Virgulate answered 19/2, 2016 at 13:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.