Polymorphism? C ++ vs Java

An attempt at polymorphism as a beginner. I think I'm trying to use the same code in different languages, but the result is not the same:

C ++

#include <iostream>
using namespace std;

class A {
    public:

    void whereami() {
        cout << "You're in A" << endl;
    }
};

class B : public A {
    public:

    void whereami() {
        cout << "You're in B" << endl;
    }
};

int main(int argc, char** argv) {
    A a;
    B b;
    a.whereami();
    b.whereami();
    A* c = new B();
    c->whereami();
    return 0;
}

Results:

You're in A
You're in B
You're in A

Java:

public class B extends A{

    void whereami() {
        System.out.println("You're in B");
    }

}

//and same for A without extends
//...


public static void main(String[] args) {
    A a = new A();
    a.whereami();
    B b = new B();
    b.whereami();
    A c = new B();
    c.whereami();
}

Results:

You're in A
You're in B
You're in B

Not sure if I am doing something wrong, or is it related to the languages ​​themselves?

+4
source share
2 answers

You need to read about the key virtualfor C ++. Without this qualifier, you have member functions in your objects. They do not follow the rules of polymorphism (dynamic binding). With the qualifier, virtualyou get methods that use dynamic binding. In Java, all instance functions are methods. You always get polymorphism.

+8

" ".

#include <iostream>
using namespace std;

class A {
    public:

    virtual void whereami() { // add keyword virtual here
        cout << "You're in A" << endl;
    }
};

class B : public A {
    public:

    void whereami() {
        cout << "You're in B" << endl;
    }
};

int main(int argc, char** argv) {
    A a;
    B b;
    a.whereami();
    b.whereami();
    A* c = new B();
    c->whereami();
    return 0;
}

Java .

+3

Source: https://habr.com/ru/post/1621546/


All Articles