You are here:

C++/abit confused

Advertisement


Question
Hello vijayan,

suppose i have a class given below:



class Person {
   public :
   Person(const char *Pname , int child_Num, int a, int b, int c, int d = 0, int e = 0);
   ~Person();/*the destructor*/
   Person();

   int getChild_Num() {
       return child_Num;
   }
   int getChild_Age(int i) {
       return child_Ages[i];
   }
   char*    getName () {
       return name;
   };
   const Person& operator=(Person &p);
   Person operator +(Person &p);

   friend ostream &operator<<(ostream &out, const Person& p);

   private:
       char *name;
       int    *child_Ages;
       int     child_Num;
};

and then the method operator =(Person p)implementation

const Person& Person:: operator= (Person p)
{
   if(this!=&p)    /*avoid invalid self-assignment*/
   {
       /*allocate address for the new spaces and copy in variables*/

       name = new char[strlen(p.name)+1];
       strcpy(name, p.name);
      
       child_Ages = new int[5];

       child_Ages[0] =  p.getChild_Age(0);
       child_Ages[1] =  p.getChild_Age(1);
       child_Ages ......

Answer
The basic idea is right; you do need to do a deep copy (allocate address for the new spaces and copy in variables). You also need to write a copy constructor, and in the assignment operator make sure that you do not forget to release the old memory once copying is done.

The copy constructor must, and the overloaded assignment operator should take its parameter by (const) reference.

see http://www.learncpp.com/cpp-tutorial/912-shallow-vs-deep-copying/

The smart way to write the person class is:

class person
{
       // ...

       private:
               std::string name ;
               std::vector<int> child_Ages;
};

The string and vector classes manage memory on their own, know how to make correct deep copies. You do not have to worry about copy and assignment, the compiler will generate the correct copy constructor and assignment operator for you.

see: http://www.cprogramming.com/tutorial/string.html
http://www.cprogramming.com/tutorial/stl/vector.html

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


vijayan

Expertise

my primary areas of interest are generic and template metaprogramming, STL, algorithms, design patterns and c++09. i would not answer questions about gui and web programming.

Experience

over 15 years

Education/Credentials
post graduate engineer

©2012 About.com, a part of The New York Times Company. All rights reserved.