0

As the title states, I want to be able to print 101 in the following code:

#include <iostream>
#include <sstream>
#include <string>

class A {
    public:
        virtual int num();  // Method I want to override
        std::string str();
};

class B: public A {
    public:
        int num();
};

int A::num(){
    return 0;  // default value
}

std::string A::str(){
    std::ostringstream s;
    s << num();
    return s.str();
}

int B::num(){
    return 101;  // overriden value
}

int main(){
    B b;
    A a = b;  // Upcast
    std::cerr << a.str() << std::endl;  // Want to print 101, but print 0

    return 0;
}

In the general case, I have multiple subclasses of of a parent (A) that implement their own logic for calculating something (num()), and the parent performs the same stuff on the output of that something (str()) for all different implementations of num(). I couldn't figure out how to do this in c++.

I come from a python background and am still learning c++. Normally this would work in python, but if this isn't a good design or not the right OOP way of doing this, feel free to offer an alternative solution that doesn't involve inheritance.

BrockLee
  • 931
  • 2
  • 9
  • 24

1 Answers1

2
A a = b;  // Upcast

This doesn't do what you think -- it creates a brand new A object, initialized with the A subobject of b.

If you want to see b itself as an A, use a reference:

A &a = b;  // Upcast
Quentin
  • 62,093
  • 7
  • 131
  • 191