Go Down

Topic: Using a method of derived class on base class (Read 801 times) previous topic - next topic

wizarcl

Hi friends, i wanna use a method of a deriveds class inside on base class.
I have 5 classes deriveds of base, and all have method check(), but is diferents and i wanna a method to call this methods inside on classe base:
Timming is base class.
Code: [Select]

...
void Timing::inpin(uint8_t pin){
digitalWrite(pin,check());
}

bool Timing::check(){
}
...
void TimerOffDelay::check(){
...
}


How i can do this?

PaulS

Quote
How i can do this?

You can't. The base class has no idea that classes have been developed that derive from it.

In the sketch, where all the classes are known. an instance of the derived class can invoke the base classes' functionality, but an instance of the base class can not invoke functionality of the derived class, since the instance is not that of the derived class.


JarkkoL

#3
Aug 01, 2013, 06:21 pm Last Edit: Aug 01, 2013, 06:25 pm by JarkkoL Reason: 1
You need to declare the function as "virtual" in the base class and override it in the derived class, e.g.
Code: [Select]

class base_class
{
  virtual bool check()=0;
};

class derived_class: public base_class
{
  virtual bool check()
  {
    // ...
  }
};

Note that the function signatures need to match for overriding to take place. Also "virtual" for the derived class isn't strictly necessary but it's good practice to add. I also declared the base_class "pure virtual" by adding =0 to the end, which means it doesn't need base class implementation and you are forced to implement it in derived class. This also isn't necessary and you could have it without and provide another implementation in the base class if that makes sense in your case.

liudr

To elaborate Jarkkol's purely virtual base class concept, a base class is only created to have other classes derive from. So it is used to set up common functions of each derived class and enforce these methods are all implemented in derived class by defining purely virtual methods as JarkkoL described. This usage is called interface. C++ has no interface, or a way to enforce a set of functions, like Java does, so it does interface indirectly with purely virtual base class. In a Java like language you will not need such a base class, but instead say

myClass implements interface1;

where the interface1 is a set of function declarations.

wizarcl

That's what I was trying to understand how to use ... Thank you so much!

liudr


That's what I was trying to understand how to use ... Thank you so much!


This library I wrote has such base class set up as an interface and a few derived classes all implementing the interface. It's an input class for keypads, rotary encoder etc.

http://liudr.wordpress.com/libraries/phi_interfaces/

It's not too hard to read through. Could be helpful to your work.


Go Up