-
problem with class
Look at this code
I dont know what is wrong
Code:
#include<iostream>
using namespace std;
class Bird
{
private:
int *years;
char *name;
public:
int Getyears() const { return *years;}
char* Getname() {return name;}
void Setyears(int year) { *years=year;}
void Setname(char i[]) { delete [] name;
name=new char [strlen(i)+1]; strcpy(name,i);}
Bird()
{
years=new int;
*years=5;
name=0;
}
~Bird()
{
delete years;
years=0;
delete [] name;
*name=0;
}
};
int main()
{
Bird p1;
cout<<"The first bird is called Tweety"<<endl;
p1.Setname("Tweety");
cout<<p1.Getname()<<" is old:"<<p1.Getyears()<<"years"<<endl;
cout<<"I incrase the years of Tweety at 6..."<<endl<<endl;
p1.Setyears(6);
cout<<"I create second bird (copy of Tweety) called Daffy"<<endl<<endl;
Bird p2(p1);
p2.Setname("Daffy");
cout<<"The first bird is called "<<p1.Getname()<<" and it's old:"<<
p1.Getyears()<<" years"<<endl;
cout<<"The second bird is called"<<p2.Getname()<<" and it's old:"<<p2.Getyears()<<" years"<<endl<<endl;
cout<<"I incrase the years of Daffy at 7..."<<endl<<endl;
p2.Setyears(7);
cout<<"The first bird is called"<<p1.Getname()<<" and it's old:"<<p1.Getyears()<<" years"<<endl;
cout<<"The second bird is called "<<p2.Getname()<<" and it's old:"<<p2.Getyears()<<" years"<<endl<<endl;
cin.get();
cin.get();
return 0;
}
I make a object p2 which is copy of p1
when i try to change the name of the bird on object p2 from tweety to Daffy i change the name on p1(i dont want that , i want p1 to have name tweety and p2 to have name daffy)
The same thing happens with the years...
Where is my mistake?
pls answer me soon
-
Firstly, this code is not indented properly.
However, the error is simple: you don't have a copy constructor. Therefore both the original and the copy point to the same character array. Changing the name in one changes it in the other. If one object becomes destructed, the other will keep pointing to released memory.
The whole problem would go away if you used a std::string for the name (as it has its own copy constructor) and an int for age (why do you think an int* is good for that?).