I have a class and in there I have a struct which contains a string. In main I declare the class, then create a struct to reach that string. How it looks like:
Class *myClass = new Class;
Class::Struct *myStruct;
myStruct = &myClass->getStruct(); // the struct is in a vector so I get it through a function
cout << myStruct->string << "\n";
So, with this method I can't reach the string in the struct, but I can the int's, float's, etc. If I change the code to this:
Class::Struct myStruct;
myStruct = myClass->getStruct();
cout << myStruct.string << "\n";
then it works.
My question is, why is the second one working, and the first not, and why only the string? It's not about life and death, because I don't really need that string, I just tested the program, but I'm really curious what's going on, because I'm still learning the language, and especially pointers.
Thanks in advance!
EDIT: Ok, so the definitions
class Class {
public:
struct Struct {
string name;
float data;
};
Class();
Struct getStruct( int i );
private:
vector<Struct> tempStruct;
};
Class::Class() {
Struct str;
str.name = "test";
str.data = 1.0f;
tempStruct.push_back( str );
}
struct Class::getStruct( int i ) {
return tempStruct[i];
}
EDIT2: That was a little mistake, but I forgot the &. But you helped me to find it.
getStruct()returns a copy of the struct from the vector, meaning in the first casemyStructhas the address of a temporary object resulting inmyStructbeing a dangling pointer.