This problem also appears in normal C++ code, but it's not a problem there because in normal C++ I can use "new" instead of "malloc".
What I want to do is make a linked list of objects that have the same interface but different functions and member variables, and was hoping to do this using members of a virtual class.
But I'm getting segmentation fault. I made the following simple example code (based on this), first in Arduino C++:
class CPolygon {
protected:
int width, height;
public:
void set_values (int a, int b)
{ width=a; height=b; }
virtual int area (void) =0;
void printarea (void)
{ Serial.println( this->area() ); }
};
class CRectangle: public CPolygon {
public:
int area (void)
{ return (width * height); }
};
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
}
void loop() {
CRectangle rect;
CPolygon * ppoly1 = ▭
ppoly1->set_values (4,5);
ppoly1->printarea();
delay(1000);
}
I also made it in normal C++, hoping to find the error (it just gives me a segmentation fault):
#include <iostream>
#include <stdlib.h>
using namespace std;
class CPolygon {
protected:
int width, height;
public:
void set_values (int a, int b)
{ width=a; height=b; }
virtual int area (void) =0;
void printarea (void)
{ cout << this->area() << endl; }
};
class CRectangle: public CPolygon {
public:
int area (void)
{ return (width * height); }
};
int main () {
CRectangle * rect;
rect = (CRectangle*) malloc(sizeof(CRectangle));
* rect = CRectangle();
CPolygon * ppoly1 = rect;
ppoly1->set_values (4,5);
ppoly1->printarea();
return 0;
}
Like I said, I tried this using new:
int main () {
CRectangle * rect;
rect = new CRectangle;
CPolygon * ppoly1 = rect;
ppoly1->set_values (4,5);
ppoly1->printarea();
return 0;
}
and that works fine.
I'm not really sure where to go from here in my debugging process. Am I doing something wrong, or is this an inherent limitation of malloc(), and thus of arv-g++?