Thursday 3 November 2011

Predict the output or error(s) for the following:

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();


}

Answer:

Say i am in someFunc


Null pointer assignment(Run-time error)


Explanation:

As the object is passed by value to SomeFunc  the destructor of the object is called when the control returns from the function. So when PrintVal is called it meets up with ptr  that has been freed.The solution is to pass the Sample object  by reference to SomeFunc:

void SomeFunc(Sample &x)


{


cout << "Say i am in someFunc " << endl;


}


because when we pass objects by refernece that object is not destroyed. while returning from the function.

2 comments: