views:

34

answers:

1
#include<iostream>
using namespace std;

class Something
{
  public:
  int j;
  Something():j(20) {cout<<"Something initialized. j="<<j<<endl;}
};

class Base
{
  private:
    Base(const Base&) {}
  public:
    Base() {}
    virtual Base *clone() { return new Base(*this); }
    virtual void ID() { cout<<"BASE"<<endl; }
};

class Derived : public Base
{
  private:
    int id;
    Something *s;
    Derived(const Derived&) {}
  public:
    Derived():id(10) {cout<<"Called constructor and allocated id"<<endl;s=new Something();}
    ~Derived() {delete s;}
    virtual Base *clone() { return new Derived(*this); }
    virtual void ID() { cout<<"DERIVED id="<<id<<endl; }
    void assignID(int i) {id=i;}
};


int main()
{
        Base* b=new Derived();
        b->ID();
        Base* c=b->clone();
        c->ID();
}//main

On running:

Called constructor and allocated id
Something initialized. j=20
DERIVED id=10
DERIVED id=0

My question is related to this, this and this post.

In the first link, Space_C0wb0y says

"Since the clone-method is a method of the actual class of the object, it can also create a deep-copy. It can access all members of the class it belongs to, so no problems there."

I don't understand how a deep copy can happen. In the program above, not even a shallow copy is happening. I need it to work even if the Base class is an abstract class. How can I do a deep copy here? Help please?

+5  A: 

Well, your copy constructor does nothing, so your clone method does nothing in the way of copying.

See line Derived(const Derived&) {}

EDIT: if you add code to copy by assignment all members of Derived, it will become a shallow copy. If you also copy (by making a new instance) your instance of Something, it will become a deep copy.

jv42
+1! The code does not copy anything. Deep copies require that the copying is done manually in the copy constructor.
elusive
I see. So the only purpose of having the clone method was to return a pointer of the Base type. A manual copy construction will be required anyway. Sigh! Thanks for the replies :)
Nav
Small addition: The default copy constructor creates a shallow copy. If you need a shallow copy of something, you do not need to do that manually.
elusive
I need a deep copy. That's why I've shown a pointer of the Something class.
Nav
@Nav: I understood that. I just wanted to point out, that a shallow copy does not require implementing a copy constructor (for the record).
elusive
Added these two functions to to the copying: Derived(const Derived} and void setID(int i)const {id=i;}but compiler says: test3.cpp: In member function ‘void Derived::setID(int) const’:test3.cpp:34: error: assignment of data-member ‘Derived::id’ in read-only structure.What am I missing?
Nav