thekevinscott
thekevinscott

Reputation: 5413

Arduino: Inheritance and arrays of pointer subclasses

This is problem #2 from this previous question:

Inheritance in Arduino Code

Building off of Steven's answer, I do need the array that holds the pointers to persist outside of its scope, which is resulting in some weird behavior.

This is my "Board" class I have so far, that contains multiple child elements:

Board.h:

#ifndef Board_h
#define Board_h

#include <StandardCplusplus.h>
#include <serstream>
#include <string>
#include <vector>
#include <iterator>

#include "Arduino.h"
#include "Marble.h"
#include "Wall.h"

class Board
{
  public:
    Board();
    void draw(double* matrix);
  private:
    Marble marble;
    //std::vector<Actor> children;
    Actor* children[2];

};
#endif

Board.cpp:

#include "Arduino.h"
#include "Board.h"
#include <math.h>

#include <iterator>
#include <vector>

Board::Board()
{

}

void Board::create(double* _matrix, int _cols, int _rows) {

  Marble *marble = new Marble();
  Wall wall;
  children[0] = marble; 

  //children.push_back(marble);
  //children.push_back(wall);


}


void Board::draw(double* matrix) {
  Serial.println("board draw");
  children[0]->speak();  
}

In my "loop" function I am calling

board.draw(matrix);

which results in some nutty Serial code being written out.

Clearly I am not understanding the ins and outs of pointers in arrays in classes here.

Upvotes: 0

Views: 639

Answers (1)

billz
billz

Reputation: 45410

You need to make Actor::speak virtual, the compiler uses dynamic binding for virtual methods.

class Actor
{
  public:
    Actor();
    virtual void speak();  // virtual
  private:
};

Upvotes: 1

Related Questions