Polymorphism? C++ vs Java
Asked Answered
F

3

8

Trying out polymorphism as a beginner. I think I am trying 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'm doing something wrong, or this has to do with the languages themselves?

Formulate answered 24/12, 2015 at 0:3 Comment(2)
youre missing the virtual keyword in whereami in the 1st program...Donela
@Reimeus: The OP also forgets to provide virtual destructor in Base class & write delete c; in the main() function.Ehrsam
M
10

You need to read up about the virtual keyword for C++. Without that qualifier, what you have are member functions in your objects. They don't follow the rules of polymorphism (dynamic binding). With the virtual qualifier you get methods, which use dynamic binding. In Java, all instance functions are methods. You always get polymorphism.

Maori answered 24/12, 2015 at 0:8 Comment(3)
With the virtual qualifier they're still member functions. C++ does not use the term "method". There are virtual member functions and non-virtual member functions. Terminology aside, though, the answer is correct.Delcine
I would never argue about C++ with Pete Becker.Maori
I forgot to say that aside from the terminology, this answer is correct.Delcine
O
5

Use "virtual functions".

#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;
}

In Java, all instance methods are virtual functions in default.

Ornery answered 24/12, 2015 at 0:9 Comment(0)
M
0

It's a bit late to answer but use override keyword in derived classes to let compiler know that you are overriding.

Mortenson answered 17/4, 2021 at 5:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.