-1

Consider the following classes:

 class Base {
 public:
     ... // include virtual destructor and rest of methods
     virtual void changeField(int val) = 0;
     virtual Base * clone() const = 0;
 };

 class Derived: public Base {
     int x;
 public:
     ... // include its destructor and rest of its methods
     void changeField(int val) { x = val; }
     Derived * clone() const { return new Derived(*this); }
 };

Suppose I have an existing Base * pointer bp that points to an Derived object. Then I call bp->clone() to make a copy and store the pointer of the resulting object in a Base * pointer, copyPointer.

When I try to changeField on the copyPointer, the value is changed, but the original object has its field also changed. Why is this? And what can I do to prevent this? Would I have to create an entirely new object from scratch?

Edit: Here is my main function in which I implement the described scenario

int main() {
     try {
        Base * copyPointer = bp->clone();
        copyPointer->changeField(5);
        cout << copyPointer->print() << endl;  //prints the field of Derived
        delete copyPointer;
      }
      catch (exception& e) {    // I also have an Exception class in my code
        cout << e.what() << endl;
      }
}
Christophe
  • 68,716
  • 7
  • 72
  • 138
CSishard
  • 21
  • 5

1 Answers1

1

Your assumption, that the function changeField() on the copyPointer changes the original object, is wrong!

I elaborated your example:

#include <iostream>
using std::cout;
using std::endl;

class Base {
     public:
     // include virtual destructor and rest of methods
     virtual void changeField(int val) = 0;
     virtual Base * clone() const = 0;
     virtual int print() const =0;
};

class Derived: public Base {
     int x;
     public:
     // include its destructor and rest of its methods
     Derived(int i):x(i)  {}
     void changeField(int val) { x = val; }
     Derived * clone() const { return new Derived(*this); }
     int print()const  { return x; }
 };
 int main() {
     Base* bp =new Derived(3);
     cout <<bp->print() <<endl;
     Base * copyPointer = bp->clone();
     copyPointer->changeField(5);
     cout <<copyPointer->print() <<endl;  //prints the field of Derived
     cout <<bp->print() <<endl;
 }

and the output is:

3
5
3
Christophe
  • 68,716
  • 7
  • 72
  • 138
Roland
  • 336
  • 2
  • 8