jeudi 18 février 2021

Understanding base to derived class casting and conversion errors

(the following is an example to simplify the explanation, but it reflects pretty well my real problem)

I have these classes and function, which i can't change or modify:

CannotChangeThis.h

class baseRectangle
{
  public:
    baseRectangle() : x(0),y(0),w(0),h(0) {}
    baseRectangle(int xx, int yy, int ww, int hh) : x(xx),y(yy),w(ww),h(hh) {}

    int x,y,w,h; // left, top, width, height
    void SetRectangle(int xx, int yy, int ww, int hh)
    {
      x=xx;y=yy;w=ww;h=hh;
    }
    int GetRight() {return w-x-1;}
    int GetBottom() {return h-y-1;}
    
    [other methods]
}
baseRectangle GetABaseRectangle();
void PassABaseRectangle(baseRectangle br);

I have a derived class that do some computation when you change the base class data:

MyNewClass.h

class DerivedRect : public BaseRectangle
{
  private:
    DoPreComputation()
    {
      r=w-x-1;b=h-y-1;
      cx=ww/2;cy=hh/2;
    }
  public:

    int r,b,cx,cy;  // right, bottom, centerX, centerY
    DerivedRect () : r(0),b(0),cx(0),cy(0) {}

    void SetRectangle(int xx,yy,ww,hh)
    {
      BaseRectangle::SetRectangle(int xx,yy,ww,hh);
      DoPreComputation();
    }
    int GetRight() {return r;}
    int GetBottom() {return b;}
    
    DerivedRect &operator=(const BaseRectangle &r1 )
    {
        if (&r1 == this) { return *this; } // prevent assigning to self
        BaseRectangle ::operator=(r1);
        DoPreComputation();
        return *this;
    }
}
DerivedRect GetADerivedRect();
void PassADerivedRect(DerivedRect dr);

My problem:

AdvRect rr;
rr = hRect; // this works

AdvRect ar = hRect; // this cause error "conversion from 'BaseRectangle ' to non-scalar type 'DerivedRect' requested"
PassADerivedRect( GetABaseRectangle() );  // Error "no known conversion for.."
PassABaseRectangle( GetADerivedRect() );  // Error "no known conversion for.."

I think i'm missing something very basic about converting or casting between base and derived classes.

I've seen here in stackoverflow what Object slicing is, but since my derived class just do "pre-computation" over the same data, i don't think that should be a problem.

What am i doing wrong?

Aucun commentaire:

Enregistrer un commentaire