Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people, just like you, are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
Solved

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

Posted on 2008-10-25
9
3,164 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
Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 

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
 
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

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Suggested Solutions

Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
Container Orchestration platforms empower organizations to scale their apps at an exceptional rate. This is the reason numerous innovation-driven companies are moving apps to an appropriated datacenter wide platform that empowers them to scale at a …
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…
The viewer will be introduced to the technique of using vectors in C++. The video will cover how to define a vector, store values in the vector and retrieve data from the values stored in the vector.

856 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