Search code examples
c++classpointerscopyprivate

How can I copy a pointer to another class within a class to another pointer in C++?


In other words, how can I take a pointer of a class-type that is within a different class and copy it to another pointer of the same class-type.

Here's an example:

class Bananas
{
    private:
        int peel;
        string color;
};

class Apples
{
    private:
        Bananas *ptr1;
        Bananas *ptr2;

    public:
        void copyPointers();
};

In the above example, I need to copy the values of ptr1 to ptr2.

Note: ptr2 is empty.

Failed Attempt #1:

memcpy(ptr2, ptr1, strlen(ptr1)+1);

Failed Attempt #2:

ptr2 = ptr1;

UPDATE:

To further explain my function:

void Apples::copyPointers()
{
    ptr2 = ptr1;
}

Solution

  • If you need to copy the value of the pointer (the memory address):

    ptr2 = ptr1;
    

    Now ptr2 will point to the same object as ptr1.

    If you need to copy the object that ptr1 points to, and assign that new object to ptr2:

    ptr2 = new Bananas(*ptr1);
    

    This will call the Bananas copy constructor with the object pointed to by ptr1. Remember to delete ptr2 afterwards (or use std::unique_ptr which does this drudgework for you automatically).