How to do propper object oriented programming in C++, late binding polymorphism?

Viewed 27

I am trying to figure out how to do oop in C++...

The issue lies with overrides. Consider the following code:

#include <iostream>

class Base {
public:

    Base() { }
    virtual void print() { 
        std::cout << "Base" << std::endl; 
    }

};

class Derrived: public Base {
public:

    Derrived() : Base() { }
    void print() override { 
        std::cout << "Derrived" << std::endl; 
    }

};


int main() {
    std::cout << "Hello, World!" << std::endl;

    Base b = Derrived();
    b.print();

    return 0;
}

When I run this program I would expect to see "Derived"! But I see "Base". So I would love to see this be possible in C++, as it is in languages like Scala, Java, C#, ... (event Rust!), but I am not sure if this is at all possible in C++.

If not maybe somebody can help me with the following situation:

std::string Value::any_to_string(std::any any) {

    std::string s = NO_VALUE;

    if (any.type() == typeid(Nothing))
        s = std::any_cast<Nothing>(any).to_string();
    if (any.type() == typeid(Boolean))
        s = std::any_cast<Boolean>(any).to_string();
    if (any.type() == typeid(Number))
        s = std::any_cast<Number>(any).to_string();
    if (any.type() == typeid(Lambda))
        s = std::any_cast<Lambda>(any).to_string();
    if (any.type() == typeid(Add))
        s = std::any_cast<Add>(any).to_string();
    if (any.type() == typeid(LiteralSet))
        s = std::any_cast<LiteralSet>(any).to_string();

    return s;
}

All of the above types inherit from a class named Value and override the method to_string(), though when casting the objects to a Value object, the definition in Value is called, rather than the one in the concrete type...

Thanks for helping me out!

1 Answers

Changing the main function to the following resolves the issue!

int main() {
    std::cout << "Hello, World!" << std::endl;

    Derrived derrived;
    Base* b = &derrived;
    b->print();

    return 0;
}

this works too!

int main() {
    std::cout << "Hello, World!" << std::endl;

    Base* b = new Derrived();
    b->print();

    return 0;
}
Related