Michal W
Michal W

Reputation: 803

Make a derived object copy from pointer

Let's say I have a class A and B where B derives from A. And later I have a pointer A* which can point to an object class A or object class B. Now I'd like to copy this object under pointer without knowledge which object is pointed to by this pointer so if there is an A object then I'd like to copy an A object but if it's B then I'd like to copy B. I'd like to omit RTTI and dynamic casting. Do you have an idea how to do it? Or must I implement something like virtual cloning function and call it explicitly?

Upvotes: 2

Views: 986

Answers (2)

CygnusX1
CygnusX1

Reputation: 21779

The cloning virtual function is the most typical approach for this, for example as

class Base {
    public: virtual Base* clone() { return new Base(*this); }
};

class Derived : public Base {
    public: virtual Base* clone() { return new Derived(*this); }
};

Sometimes however, when you have a pointer to Derived and you clone it, you suddenly have a pointer to Base while you know that it is derived. A down-cast is then needed, if you want to access Derived-specific members.

According to C++98-standard you can actually change the return type to the derived type, e.g.

class Base {
    public: virtual Base* clone() { return new Base(*this); }
};

class Derived : Base {
    public: virtual Derived* clone() { return new Derived(*this); } //will overload Base::clone
};

Upvotes: 4

cpp
cpp

Reputation: 3801

In the simple case of memberwise copy it seems strightforward:

#include<iostream>
using namespace std;

class A{
public:
    ~A(){}
    A() : _x('A') {}
    void foo() { cout << _x << endl; }   
protected:
    char _x;    
};

class B : public A{
public:
    ~B(){}
    B() { _x = 'B';}
};

int main()
{
    A* a = new A();
    A* b = new B();

    A* c(a);
    c->foo();  //A

    A* d(b);
    d->foo();   //B

    delete a,b;
}

Upvotes: 0

Related Questions