On Jul 29, 9:38 pm, Roy <royash...@gmail.com> wrote:
On Jul 30, 9:24 am, Ian Collins <ian-n...@hotmail.com> wrote:
Snipped previous iterations.
heres what i get :-(
I have understood The NULL thing , i have modified the code to
#include<iostream>
using namespace std;
class cpchk{
private:
char* name;
int num;
public:
// Methods for name
char* getname()const{
cout<<"Address:Name>>"<<&name<<endl;
Here you are not printing the content of the pointer, but the address
of the pointer. This will not change during the live of the project.
Change this too (for example):
cout<<"Address:Name>>"<< hex << (long)name<<endl;
Don't forget to include <iomanip> for "hex".
return name;
}
void setname(const char* acname){
if(name==NULL)
name=(char*)malloc((strlen(acname)+1)*sizeof(char));
In C++, you'd generally use "new" here, not "malloc".
else{
free(name);
name=NULL;
name=(char*)malloc((strlen(acname)+1)*sizeof(char));
}
The if/else logic here can be simplified and redundant code can be
removed.
You think about how - ask if you need to.
strcpy(name,acname);
}
// Methods for num
int getnum()const{
cout<<"Address:Num>>"<<&num<<endl;
return num;
}
void setnum(const int inum){
num=inum;
}
// Constructors
cpchk(){
cout<<"Constructor called"<<endl;
name=NULL;
num=0;
Lookup "initialization lists" in this newsgroup.
}
cpchk(char* acname,int inum){
name=(char*)malloc((strlen(acname)+1)*sizeof(char));
strcpy(name,acname);
}
inum is not used in this function.
// Destructor
~cpchk(){
cout<<"Address:Object>>"<<this<<endl;
cout<<"Destructor called"<<endl;
cout<<"Address:Name>>"<<&name<<endl;
Same problem here. You're displaying the address of the pointer, not
it's contents (what it is pointing too).
cout<<"Address:Num>>"<<&num<<endl;
if(name!=NULL)
free(name);
You can use "delete []" here if you use "new" to allocate the string.
name=NULL;
}
};
int main(int argc,char** argv){
cpchk a,b;
a.setname("Hitesh");
a.setnum(10);
b.setname("Rajesh");
b.setnum(30);
cout<<endl<<"Before Assignent"<<endl;
cout<<"Object A"<<endl;
cout<<&a<<endl;
cout<<a.getname()<<endl;
cout<<a.getnum()<<endl;
cout<<"Object B"<<endl;
cout<<&b<<endl;
cout<<b.getname()<<endl;
cout<<b.getnum()<<endl;
a=b;
This doesn't call the copy constructor (the title of your thread), but
instead invokes the assignment operator.
cout<<endl<<"After Assignent"<<endl;
cout<<"Object A"<<endl;
cout<<&a<<endl;
cout<<a.getname()<<endl;
cout<<a.getnum()<<endl;
cout<<"Object B"<<endl;
cout<<&b<<endl;
cout<<b.getname()<<endl;
cout<<b.getnum()<<endl;
return 0;
}
Hope this helps.
Cheers,
Andre
1.
Don't forget to include <iomanip> for "hex".
2.
types . Is it wrong ?I guess i should search ?
3.
4. Finally i have proff that why copy constructor is vital !