Search code examples
c++eclipseclassinstancevirtual

How to use virtual class in c++ to call method from other class?


I am trying to call a method from one class in another class using virtual classes. I tried several ways of instantiating the virtual class but always get some errors, what am I doing wrong? These are the three code pieces.

I am trying to use a virtual class SimData.h:

#ifndef SIMDATA_H_
#define SIMDATA_H_

class SimData
{
public:
virtual void onSimUpdate(int id)=0;
};

#endif /* SIMDATA_H_ */

To call a function from maintask.h

...
class maintask : public SimData
{
public:
     virtual void onSimUpdate(int id);
...

In another class Select.cpp

.....
SimData* dat;

dat->onSimUpdate(value1); --->HERE IS THE ERROR THAT IT IS NOT INITIALIZED
.....

Do you know how I call the abstract class correctly in the Select.cpp file?

Thank you.


Solution

  • You have a pointer to SimData. You need to make it point to an instance. For example,

    SimData* dat;
    maintask m;
    dat = &m; // dat now points to m
    dat->onSimUpdate(value1); // OK now
    

    Note that calling new maintask() would yield a pointer to a maintask that you can assign to dat. I haven't used that example because dynamic allocation and polymorphism via pointers are two separate issues. Furthermore, dealing with raw newed pointers is fraught with peril.

    Here is a more realistic example, still without dynamic allocation, and even without pointers:

    void foo(SimData& data, int x) { dat.onSimUpdate(x); }
    
    maintask m;
    foo(m, 42);