Problems with the run time code

#include<iostream.h>
#include<conio.h>
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()
{
int *ptr;
Sample s1= 10;
SomeFunc(s1);
s1.PrintVal();
cout<<"\n"<<*ptr;
getch();
}
here is the code...
its compilation is ok
but at run time its not wrkin..
wat can be the bug in it
help would be appreciated.
wrkin?

The problem is you're copying the object (passing by value to SomeFunc, which copies the object), but you don't have a proper copy constructor, and so the same pointer is being deleted twice.

Possible Solutions:

1) Pass by reference/const reference to SomeFunc instead of passing by value:

1
2
3
4
void SomeFunc(const Sample& x)
{
  //...
}


2) Write a proper copy constructor (and assignment operator) so that the object can be properly copied:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

class Sample
{
public:

  //...

  Sample(const Sample& r)
  {
    ptr = new int( *(r.ptr) );
  }

  Sample& operator = (const Sample& r)
  {
    *ptr = *(r.ptr);
  }

  //...
};



3) Both of the above
1) Thank you for using getchar() instead of system("pause");
2) Please review spelling and the conditional in English (the latter is only necessary if you are a native speaker)
3) Since you do not give us a clue as to what it is supposed to output and what it is actually doing the only thing that I can think of is that you never initialize ptr. Since you then proceed to dereference ptr, *ptr, this will naturally point to either the 0 mem address or another address that you are not allowed to use. As a result the OS will give you a segfault, which throws an exception. There are two ways to handle this, either initialize ptr or use try, catch blocks. The latter is probably a little advanced for you, but if you want to impress your instructor, use try-catch statements.
Topic archived. No new replies allowed.