How to use an inherited variable in C ++

I have a question for inherited variables. Parts of my source code:

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 } } 

The RectilinearTransducer contains m_piston, which is always a RectlinearPiston! But m_piston is inherited by the Transducer class, and I cannot use the setGridSize () function.

error message: error C2039: "setGridSize": no "Piston" element

The setGridSize function does not exist in the Piston class ...

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

thanks for the help

+4
source share
2 answers

If you cannot make setGridSize virtual function in the parent, then you can add a function that simply adds m_piston to RectangularPiston* , then calls this function when your class must reference m_piston .

 RectangularPiston* getRecPiston() { return static_cast<RectangularPiston*>(m_piston); } bool setGridSizeOfPiston(...) { return getRecPiston()->setGridSize(...) } 
+2
source

You need to make the setGridSize virtual Piston function (either pure virtual or another).

eg

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

Source: https://habr.com/ru/post/1495152/


All Articles