javac++finalnon-virtual-interface

java final methods vs c++ nonvirtual functions


are java final methods and c++ nonvirtual methods different or the same? How?


Solution

  • You can still declare non-virtual member functions with the same signature in inheriting classes in C++, where-as Java explicitly forbids declaring methods with the same signature in which the base class declares that method final. Virtuality in C++ just helps find the correct function to call when dealing with inheritance/polymorphism.

    Example:

    #include <iostream>
    
    class Base
    {
    public:
        void doIt()
        {
            std::cout << "from Base.doIt()" << std::endl;
        }
    };
    
    class Child : public Base
    {
    public:
    
        void doIt()
        {
            std::cout << "from Child.doIt()" << std::endl;
        }
    };
    
    int main()
    {
        Base a;
        a.doIt(); // calls Base.doIt()
        Child b;
        b.doIt(); // calls Child.doIt()
        Base *c = new Base();
        c->doIt(); // calls Base.doIt()
        Child *d = new Child();
        d->doIt(); // calls Child.doIt()
        Base *e = new Child();
        e->doIt(); // calls Base.doIt()
        std::cin.ignore();
        return 0;
    }
    

    The comparable example in Java using final will result in a compiler error:

    public class Base
    {
        public final void doIt()
        {
            System.out.println("In Base.doIt()");
        }
    }
    
    public class Child extends Base
    {
        public void doIt() // compiler error: Cannot overload the final method from Base
        {
            System.out.println("In Child.doIt()");
        }
    }
    

    For more explanation on Polymorphism in C++, see cplusplus.com: Polymorphism

    Effictively, though, both methods have similar goals: to prevent overriding of a function in the base class. They just go about it in slightly different ways.