how to use inherited variable in c++

493 views Asked by At

I have a question to inherited variables. Parts of my sourcecode:

class Piston{           //abstract class        
   ...                  //virtual functions        
};

class RectangularPiston: public Piston
{
  ...                   //non virtual implementation of the Piston functions
  bool setGridSize(...) //this function doesn't exists in the Piston class
  {
    ...
  }
}

class Transducer{       //abstract class
    ...                 //virtual functions
  protected:
    Piston *m_piston;
};

class RectilinearTransducer: public Transducer
{
    ... //non virtual implementation of the Piston functions
    bool setGridSizeOfPiston(...)
    {
        return m_piston->setGridSize(...);  //doesn't work
    }

}

RectilinearTransducer holds a m_piston, which is always a RectlinearPiston! But m_piston is inherited by the Transducer class and I can't use the setGridSize()-function.

error message: error C2039: 'setGridSize': Is no element of 'Piston'

The function setGridSize doesn't exists in the Piston class...

How can I solve this Problem? Should I overwrite the m_piston variable like I can do it with virtual functions? The m_piston variable exists as Piston* m_piston, because I inherited it by the Transducer class.

Thanks for help

2

There are 2 answers

1
Hna On BEST ANSWER

If you can't make setGridSize a virtual function in the parent then you might want to add a function that simply casts m_piston to RectangularPiston* then call this function when your class needs to refer to m_piston.

RectangularPiston* getRecPiston() {
    return static_cast<RectangularPiston*>(m_piston);
}

bool setGridSizeOfPiston(...) {
        return getRecPiston()->setGridSize(...)        
}
0
Ed Heal On

You need to make setGridSize a virtual function of Piston (either pure virtual or otherwise).

e.g

class Piston {
  protected: (or public)
     virutal bool setGridSize(..) = 0;
...