-1

That's an Arduino project, which has a mode button. The button changes the current application variable to be player/radio/navigation/phone. All the applications inherit from "App".

If I run "apps[0]->volume_up();", it shouts at me that there's no method volume_up in application. If I add it to App, it executes the volume_up in App and not in Player.

What am I doing wrong?

int index = 0;
App *apps[4];

void setup(){
    Player *player = new Player();
    Radio *radio = new Radio();
    Navigation *navigation = new Navigation();
    Phone *phone = new Phone();
    apps[0] = player;
    apps[1] = radio;
    apps[2] = navigation;
    apps[3] = phone;
}

void loop(){
    int sensorValue = analogRead(A0);

    if (sensorValue == 156 || sensorValue == 157){ // Mode button
        index = (index + 1) % (sizeof(apps)/sizeof(apps[0]));
        delay(300);
    }

    if (sensorValue == 24 || sensorValue == 23){ // Volume button
        apps[index]->volume_up();
        delay(100);
    }
}

Edit

#ifndef App_H
#define App_H

#include "Arduino.h"

class App {
    public:
        void volume_up();
    };

#endif


#include "App.h"

void App::volume_up(){
    Serial.println("VOLUME_UP");
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Yaron Yosef
  • 447
  • 3
  • 12

1 Answers1

0

If you want to call the method from the parent, either use App::volume_up() in your subclasses' methods. Or mark the method as virtual like in

virtual void App::volume_up(){ }

and you can call it in the subclasses.

You'll need to inherit class App in your classes Phone, etc.

class Phone : public App {

};

Then either

 void Phone::volume_up() { App::volume_up(); }

if you don't use virtual methods, or

 void Phone::volume_up() { //Phone implementation }

if you use virtual methods.

To use runtime-polymorphism you'll need to create pointers, as you did!

Look at Wikipedia article Virtual function and Stack Overflow question Call a C++ base class method automatically.

Community
  • 1
  • 1
bash.d
  • 13,029
  • 3
  • 29
  • 42