Could you please help with this code?
The program prints bullshit when executing the marked line. I know that there is some problem with pointers, but I cannot understand what it is wrong.
class B {
public:
virtual const char* getStr();
virtual int getInt();
B(const char*, int);
private:
const char* p_str;
int m_int;
};
B::B(const char* str, int i){
p_str=str;
m_int=i;
}
const char* B::getStr() {
return p_str;
}
int B::getInt(){
return m_int;
}
B* items[]={&B("test", 1)};
void setup(){
Serial.begin(9600);
Serial.println("SETUP");
}
void loop() {
Serial.println("LOOP");
/// The problem is here /////////
Serial.println(items[0]->getInt());
////////////////////////////////////
delay(100000);
}
Test it with the (newer and better) Arduino IDE 1.5.8 BETA.
This line doesn't even pass the compiler : B * items [ ] = { & B ( "test" , 1 ) } ;
"error: taking address of temporary"
You have to create a class 'B' somehow.
Is it a list of classes, and you are only initializing the first one ? That should be a linked list.
How does the compiler know how big the array of pointers will be ?
This creates the class : B item0 ( "test" , 1) ;
This creates an array with pointers, and this prints the right values in your sketch:
B item0("test", 1);
B item1("hello", 5);
B* items[] = { &item0, &item1 };
I understand the problem now. In my version of IDE (1.0.6) this code is compiled without any errors.
The error you got: "taking address of temporary" describes it all: when the array is initialized, the scope of object B is limited, so the reference to it becomes invalid afterwards.
Peter_n:
Is it a list of classes, and you are only initializing the first one ? That should be a linked list.
How does the compiler know how big the array of pointers will be ?
Actually in the real code this is a list of objects of different types (there is some class hierarchy), I don't need a linked list. And the size of the array of pointers is known by the compiler - it equals 1.