c++oop

C++ classes , Object oriented programming


I have a very simple class named person which is given below , I have a problem with only two functions , i.e setstring () function and setname() function , I am calling setstring() function from the setname function. The only problem is when in the main function I write
Object.setname(“Zia”);
The result is ok as shown in the output screen, Now when I write
Object.setname(“Zia ur Rahman”);
Nothing is displayed as you can see the output screen.

I know the problem is when I pass the name pointer to setstring () function but I am confused about it please explain it in detail that what is happening here.

#include<iostream.h>
class person
{
char* name;
public:
person();
void setname(const char*);
void setstring(const char*, char*);
void print()const;
};
person::person()
{
name=new char[3];
strcpy(name,"NILL");
name[3]='\0';
}
void person::setstring(const char* s, char*p)
{
if(s!=NULL)
{
delete[] p;
p=new char[strlen(s)];
strcpy(p,s);
p[strlen(s)]='\0';
}
}
void person::setname(const char* n)
{
setstring(n, name);//passing data member name
}
void person::print()const
{
cout<<"Name: "<<name<<endl;
}
main()
{
person object;
object.setname("Zia ur Rahman");
object.print();
system("pause");
}

alt text http://img264.imageshack.us/img264/8867/inheritanceimage004.jpg

alt text http://img263.imageshack.us/img263/3770/inheritanceimage003.jpg


Solution

  • The specific reason that nothing is being printed is that in setstring, p is copy of the name pointer, not a reference to it. Try changing the signature of setstring to:

    void setstring(const char* s, char*& p);
    

    (note the &).

    See the other answers for other significant errors in the code - unless these problems are fixed, you are likely to get crashes or strange behaviour.

    And unless the purpose of the code is just to learn dynamic arrays, use std::string instead :-).