Logo 
Search:

C++ Programming FAQ

Submit Interview FAQ
Home » Interview FAQ » C++ ProgrammingRSS Feeds

C++ programming practical question 1

  Shared By: Adah Miller    Date: Jan 24    Category: C++ Programming    Views: 81

Answer:

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.

Share: 
 

Didn't find what you were looking for? Find more on C++ programming practical question 1 Or get search suggestion and latest updates.


Your Comment
  • Comment should be atleast 30 Characters.
  • Please put code inside [Code] your code [/Code].


Tagged: