Hello overy one,
i had aproblem with the following program can any one help me with it plz
#include<iostream.h>
class vector{
private:
int *p;
int n;
public:
vector()
{
p=NULL;
n=0;
}
vector(int a)
{
n=a;
p=new int [n];
}
In your destructor you should check if the pointer is already null before deleting it. Because of the way you setup your default constructor there's a chance that the pointer p could be null when the object is destroyed. This also applies to all of your methods. If the user of your code were to use the default constructor and then call any of the methods they would get a null pointer exception.
Actually, the C++ standard says that you may delete a null pointer, and it will have no effect, so that's not really a problem. You do however need an assignment operator to handle v2=v1.copy(). Please post the compiler errors in the future; having output makes issues much easier to diagnose.
1. v1.copy() returns a temporary wich is assigned to v2.
2. When the temporary is destoryed, it deletes it's array which is shared by v2.
3. When v2 dies, it calls delete on an array that's already been freed. With any luck, you get a crash. It's even worse if it fails without some like of fight.
thanks for eavery one how help in this problem it's solved by using copy constructor to copy the content of the object before delete it
// this result of using copy constructor
#include<iostream.h>
class vector{
private:
int *p;
int n;
public:
vector()
{
cout<<"Default Constructor"<<endl;
p=NULL;
n=0;
}
vector(int a)
{
cout<<"overloading Constructor One input"<<endl;
n=a;
p=new int [n];
}
vector(int a[],int b)
{
cout<<"Overloading Constructor Two input"<<endl;
n=b;
p=new int [n];
for(int i=0;i<n;i++)
p[i]=a[i];
}
vector(vector &v)
{
cout<<"Copy Constructor"<<endl;
n=v.n;
p=new int [n];
for(int i=0;i<n;i++)
p[i]=v.p[i];