Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ inheritance - invalid initialization of reference type

I wrote the following code:

class DoubleClass;
class IntClass;

class Number {
public:
    virtual Number& addInt(IntClass& x)=0;
    virtual Number& addDouble(DoubleClass& x)=0;
    virtual Number& operator+(Number& x) = 0;
};

class IntClass : public Number {
private:
    int num;
public:
    IntClass(int num) : num(num) { }
    Number& addInt(IntClass& x) { return x; }
    **Number& addDouble(DoubleClass& x) { return x; }**
    Number& operator+(Number& x) { return x; }
};

class DoubleClass: public Number {
private:
    double num;
public:
    DoubleClass(double num) : num(num) {}
    double get_number() { return num; }
    Number& addInt(IntClass& x) {
        return x;
    }
    Number& addDouble(DoubleClass& x) { return x; }
    Number& operator+(Number& x) { return x; }
};

Thanks Diego Sevilla, I did what you said and it worked. One more question, I'm supposed to write the function: Number& add(Number& x,Number& y) Is the only way of implementing it is to do dynamic_cast for x and y for all possibilities (casting x and y to int, and if an exception is thrown then casting x to double and y to double, and so on), or is there an easier way?

like image 649
Shmoopy Avatar asked Apr 20 '26 03:04

Shmoopy


2 Answers

At that point the compiler doesn't know DoubleClass inherits from Number. You should separate class declaration from method implementation. For example:

class IntClass : public Number {
// ...

  Number& addDouble(DoubleClass& x); // Note: no implementation
};

class DoubleClass : public Number
{
// ...
};

inline Number& IntClass::addDouble(DoubleClass& x) { return x; } // Won't fail now
like image 75
Diego Sevilla Avatar answered Apr 21 '26 18:04

Diego Sevilla


You haven't defined DoubleClass, so you can't do anything with the reference other than take the address of the object and pass it around.

like image 44
Puppy Avatar answered Apr 21 '26 18:04

Puppy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!