Inheritance usage resulting in code restart.

kreakemp
Posts: 1
Joined: Mon Nov 18, 2019 10:45 am

Inheritance usage resulting in code restart.

Postby kreakemp » Mon Nov 18, 2019 11:13 am

When I am using inheritance and trying to call the child class function using base class pointer code is restarting. When using the child class pointer then also code is restarting. But when using it with out inheritance its working fine. Kindly help me to resolve this.

Code using base class pointer, code is restart when trying to call getabc().
class base{
public:
virtual int getabc() = 0;
};

class test: public base{
public:
int getabc(){
Serial.println("okk");
return 1;
}
};

base* ptr;
void setup() {
Serial.begin(115200);
// put your setup code here, to run once:
ptr = (test*)malloc(sizeof(test));

while(!Serial);
ptr->getabc();
}

void loop() {
ptr->getabc();
Serial.println("okk");
delay(5000);
}

When using the child class pointer then also code is restarting.
Following code is also restarting :
class base{
public:
virtual int getabc() = 0;
};

class test: public base{
public:
int getabc(){
Serial.println("okk");
return 1;
}
};

test* ptr;
void setup() {
Serial.begin(115200);
// put your setup code here, to run once:
ptr = (test*)malloc(sizeof(test));

while(!Serial);
ptr->getabc();
}

void loop() {
ptr->getabc();
Serial.println("okk");
delay(5000);
}


But when using it with out inheritance its working fine. Kindly help me to resolve this.
Code that is working:

class base{
public:
virtual int getabc() = 0;
};

class test{
public:
int getabc(){
Serial.println("okk");
return 1;
}
};

test* ptr;
void setup() {
Serial.begin(115200);
// put your setup code here, to run once:
ptr = (test*)malloc(sizeof(test));

while(!Serial);
ptr->getabc();
}

void loop() {
ptr->getabc();
Serial.println("okk");
delay(5000);
}

nvannote
Posts: 51
Joined: Thu Nov 14, 2019 10:42 pm

Re: Inheritance usage resulting in code restart.

Postby nvannote » Tue Nov 19, 2019 7:28 pm

Hi kreakemp,

Your using malloc to allocate a virtual C++ class which will certainly not initialize it correctly and will also not call any constructors. This will crash and burn on any platform.

Replace that malloc with.

Code: Select all

ptr = new test();
In the case when it works without inheritance; there is no virtual function table to initialize and you get lucky as it is just a empty struct with associated methods.

Also keep in mind that not all C++ classes need to be allocated/managed on the heap (with new/delete); They can be stack variables as well which will help with performance if your design allows it.

Regards,

Neil

Who is online

Users browsing this forum: Bing [Bot], Google [Bot] and 115 guests