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);
}
Inheritance usage resulting in code restart.
Re: Inheritance usage resulting in code restart.
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.
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
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();
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], julcol and 99 guests