Solved

How do I copy one object contents to another object in C++?

Posted on 2008-10-25
9
3,158 Views
Last Modified: 2012-05-05
Hi I have problem in how to copy an objects contents to another object.
For example I have
class base{
        main() {
                   base *p1=new base ();
                   base *p2 = new base();
                  // do some operation with p1
                 delete p1;
                  //Copy p2 contents to p1?????????
       }
};
In the above example how do I copy the contents from p1 object  p2 to another object p1?
0
Comment
Question by:Beebutter
  • 3
  • 3
  • 2
  • +1
9 Comments
 
LVL 14

Expert Comment

by:Farzad Akbarnejad
ID: 22806334
Hello,
Here is a Sample code:


#include <iostream.h>
 

class base {

private:

	int m;

public:

	int getM(void) {return m;}

	void setM(int m_) {m = m_;}

};
 

void main()

{

   base *p1=new base();

   p1 ->setM(12);

   base *p2=new base();

   p2 ->setM(14);

   // do some operation with p1

   delete p1;

   //Copy p2 contents to p1

   p1 = new base(*p2);   // Copy Constructor.

   cout << p1->getM() << endl;

   return;

}

Open in new window

0
 
LVL 14

Expert Comment

by:Farzad Akbarnejad
ID: 22806341
0
 
LVL 13

Expert Comment

by:numberkruncher
ID: 22806597
You could use a copy constructor to duplicate information from another object instance. Or you could create a copy method which returns a pointer to a duplicate instance. Which ever you find more appropriate:
class base {

public:

        base(base& copyFrom)

        {

                setM(copyFrom.getM());

        }

// OR:

        base* getCopy()

        {

                base *pCopy = new base();

                pCopy->setM(getM());

                return pCopy;

        }

private:

        int m;

public:

        int getM(void) {return m;}

        void setM(int m_) {m = m_;}

};

 

void main()

{

        // Either

        base *p1 = new base();

        p1->setM(42);

        base *p2 = new base(*p1);
 

        // Or

        base *p1 = new base();

        p1->setM(42);

        base *p2 = p1->getCopy();
 

        // Not forgetting to cleanup afterwards.

        delete p1;

        delete p2;

}

Open in new window

0
 

Author Comment

by:Beebutter
ID: 22806918
In my case I am trying to copy contents of one binary search tree (p1) to another (p2).
It is not getting copied properly.
Because as I
// do some search  and remove operations with p1
   delete p1;
   //Copy p2 contents to p1
   p1 = new base(*p2);   // Copy

Again I start doing some remove element operations with p1, but the contents are not properly getting removed. What to do?
0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
LVL 13

Expert Comment

by:numberkruncher
ID: 22807313
In your copy constructor of your class "base", are you just copying references to tree nodes, or are you also creating an actual copy.

i.e.

// SAFER
base(const base& copyRef)
{
     // Create a copy of your binary nodes.
     // Inside your BinaryNode copy constructor you would also need to clone all of its child nodes.
     // And for each child node, you must recursively clone its child nodes.
     this->pBinaryNode = new BinaryNode(copyRef.pBinaryNode);
}

// LESS SAFE
base(base& copyRef)
{
     // This just references the input binary tree...So if an item were to be removed from your
     // original object (p2) then it would also be removed from (p1) because it's the same memory.
     this->pBinaryNode = copyRef.pBinaryNode;
}
0
 

Author Comment

by:Beebutter
ID: 22807360
I want to copy all the contents That is  an actual copy of all the elements in BST p2 to p1.
Please be more descriptive of the actual solution that I need to follow by giving some code snippet.
0
 
LVL 13

Accepted Solution

by:
numberkruncher earned 500 total points
ID: 22807534
Could you post your header file which contains "base" and the header file which describes your data structure? Without understanding how you are storing your information it is difficult to suggest a more detailed solution.

I will give an example based upon the following.

// Header File
class BinaryNode
{
public:
    BinaryNode(BinaryNode& copyNode);

    int mySpecialData;

    BinaryNode *pParentNode;
    BinaryNode *pNode1;
    BinaryNode *pNode2;
}

// Source File
BinaryNode::BinaryNode(BinaryNode& copyNode)
{
     // Clone other node information.
     this->mySpecialData = copyNode.mySpecialData;

     // Clone child nodes - Recursive approach.
     this->pNode1 = new BinaryNode(*copyNode.pNode1);
     this->pNode2 = new BinaryNode(*copyNode.pNode2);
}


// Source File
base::base(const base& copyBase)
{
    this->pRootNode = new BinaryNode(*copyBase.pRootNode);
}


// Implementation File
void foo(base *p2)
{
    base *p1 = new base(*p2);
}
0
 
LVL 39

Expert Comment

by:itsmeandnobodyelse
ID: 22812420
To add to above information:

In C++ the compiler will create a copy constructor for you, if you don't provide one yourself. So if you have

  base* p1 = new base;
  // fill the base now
  ...
  base* p2 = new base(*p1);
 
 the p2 points to a structure in memory which is an identical copy of the structure pointed to by p1. However, such a copy is called a flat copy cause in case of member pointers you only get a copy of the address stored in the pointer and *not* a copy of the object or data the pointer is pointing to. Hence, if you were deleting your p1 pointer in the above sample, and the destructor deletes all nodes of the tree p1 is pointing to. Then, the nodes of p2 now all were invalid and if you access the p2 tree you most probably will crash because of that. The (only) way out is to provide a copy constructor for class base which makes a deep copy, i. e. which don't assign the pointer addresses of the nodes in the tree but creates new nodes and do the chaining between all the new pointers. That way, p2 would point to a complete copy of the tree but would not get a problem when the first tree was deleted or updated.
 
>>>> Please be more descriptive of the actual solution that I need to follow by giving some code snippet.

If I was correct you didn't post any code so far. Please post the contents of your header for the BST tree (in the Code Snippet Box if possible) as numberkruncher has required as well.
0
 

Author Closing Comment

by:Beebutter
ID: 31510053
Thank you very much. Th eexpalantion made me understand the error I was committing while copying, though it was not the direct solution.
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Article by: SunnyDark
This article's goal is to present you with an easy to use XML wrapper for C++ and also present some interesting techniques that you might use with MS C++. The reason I built this class is to ease the pain of using XML files with C++, since there is…
  Included as part of the C++ Standard Template Library (STL) is a collection of generic containers. Each of these containers serves a different purpose and has different pros and cons. It is often difficult to decide which container to use and …
The goal of the tutorial is to teach the user how to use functions in C++. The video will cover how to define functions, how to call functions and how to create functions prototypes. Microsoft Visual C++ 2010 Express will be used as a text editor an…
The goal of the video will be to teach the user the difference and consequence of passing data by value vs passing data by reference in C++. An example of passing data by value as well as an example of passing data by reference will be be given. Bot…

932 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now