Why isn't hiding of virtual functions/methods allowed in Java and C++?

Viewed 162
#include <iostream>
class A{
    public:
        void k(){
            std::cout << "k from A";
        }
};
class B:public A{
    public:
        int k(){
            std::cout << "k from B"; 
            return 0;
        }
};
int main(){
    B obj;
    obj.k();

    return 0;
}

without virtual it's working fine, But When I changed A's function to virtual then It's saying return type should be same why?

I tried same thing in Java:

class X{
    public void k(){
        System.out.println("k From X");
    }
}
public class Y{
    public int k(){
        System.out.println("k From Y");
        return 0;
    }
}

Java also showing error when I tried different return type in sub-class. ( I think because by default all instance methods are virtual by default) I was expecting int k() should hide void k() and int k() should invoke from Y's object.

So I think it's problem with virtual. Why child class should be use same return type when function declared as virtual?

If it polymorphic behavior problem. Then I think object is enough to determined the function calling.

Example:

class X{
    public void k(){
        System.out.println("k From X");
    }
}
public class Y extends X{
    public int k(){
        System.out.println("k From Y");
        return 0;
    }
    public static void main(String[] args){
        X obj=new Y();
        obj.k(); // object Y found now just call k() from Y.
    }
}

Why can't we change return type in sub-class or child class?

4 Answers
Related