Please explain why s1.printVal causes a dangling pointer error. Isn't the s1 object, i.e. its pointer, still accessible until it's destroyed?
class Sample
{
public:
int *ptr;
Sample(int i)
{
ptr = new int(i);
}
~Sample()
{
delete ptr;
}
void PrintVal()
{
cout << "The value is " << *ptr;
}
};
void SomeFunc(Sample x)
{
cout << "Say i am in someFunc " << endl;
}
int main()
{
Sample s1 = 10;
SomeFunc(s1);
s1.PrintVal(); // dangling pointer
}
Source - http://www.techinterviews.com/c-object-oriented-questions
thanks