Solved

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

Posted on 2008-10-25
9
3,156 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
6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

 
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

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Introduction This article is the first in a series of articles about the C/C++ Visual Studio Express debugger.  It provides a quick start guide in using the debugger. Part 2 focuses on additional topics in breakpoints.  Lastly, Part 3 focuses on th…
IntroductionThis article is the second in a three part article series on the Visual Studio 2008 Debugger.  It provides tips in setting and using breakpoints. If not familiar with this debugger, you can find a basic introduction in the EE article loc…
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 viewer will learn how to pass data into a function in C++. This is one step further in using functions. Instead of only printing text onto the console, the function will be able to perform calculations with argumentents given by the user.

705 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

16 Experts available now in Live!

Get 1:1 Help Now