Could somebody please explain to me why does this code only print "42" instead of "created\n42"?
#include <iostream>
#include <string>
#include <memory>
using namespace std;
class MyClass
{
public:
MyClass() {cout<<"created"<<endl;};
int solution() {return 42;}
virtual ~MyClass() {};
};
int main(int argc, char *argv[])
{
auto_ptr<MyClass> ptr;
cout<<ptr->solution()<<endl;
return 0;
}
BTW I tried this code with different values in solution and I always get the "right" value, so it doesn't seem to be a random lucky value.
Because it exhibits undefined behaviour - you dereference a null pointer.
When you say:
auto_ptr<MyClass> ptr;
you create an autopointer which doesn't point to anything. This is equivalent to saying:
MyClass * ptr = NULL;
Then when you say:
cout<<ptr->solution()<<endl;
you dereference this null pointer. Doing that is undefined in C++ - for your implementation, it appears to work.