C++ Problem: Class Promotion using derived class

Posted by Michael Fitzpatrick on Stack Overflow See other posts from Stack Overflow or by Michael Fitzpatrick
Published on 2011-06-24T23:45:10Z Indexed on 2011/06/25 0:22 UTC
Read the original article Hit count: 172

I have a class for Float32 that is derived from Float32_base


    class Float32_base {
        public:
        // Constructors
        Float32_base(float x) : value(x) {};
        Float32_base(void) : value(0) {};
        operator float32(void) {return value;};
        Float32_base operator =(float x) {value = x; return *this;};
        Float32_base operator +(float x) const { return value + x;};

    protected:
        float value;

    }

    class Float32 : public Float32_base {
        public:
        float Tad() {
            return value + .01;
        }
    }

    int main() {
        Float32 x, y, z;
        x = 1; y = 2;

    // WILL NOT COMPILE!
        z = (x + y).Tad(); 

    // COMPILES OK
        z = ((Float32)(x + y)).Tad(); 
    }

The issue is that the + operator returns a Float32_base and Tad() is not in that class. But 'x' and 'y' are Float32's.

Is there a way that I can get the code in the first line to compile without having to resort to a typecast like I did on the next line?

© Stack Overflow or respective owner

Related posts about c++

Related posts about inheritance