Given the code :
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();
}
The output is :
Say i am in someFunc
Null pointer assignment(Run-time error)
I'm not able to understand why the second line of output comes. The second line of the output. I think that the compiler supplies a copy constructor when it is not explicitly specified. So, in the function SomeFunc(Sample x), the local object to SomeFunc() which is X of Sample type should be created and destroyed and the Sample type object (s1) in main() should remain intact and should be freed only after main exits. Please answer why the above behaviour is happening?