Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making a copy of an object of abstract base class

If I have a pointer to an object that derives from an abstract base class (so I cannot create an new object of that class), and I wish to make a deep copy of said object, is there a more concise way of accomplishing that than to have the abstract base class create a new pure virtual copy function that every inheriting class has to implement?

like image 542
wrongusername Avatar asked Jan 21 '11 03:01

wrongusername


People also ask

Can we make an instance of an abstract base class?

We cannot instantiate an abstract class in Java because it is abstract, it is not complete, hence it cannot be used.

Can you create an object of an abstract class C++?

You can't create an object of an abstract class type. However, you can use pointers and references to abstract class types. You create an abstract class by declaring at least one pure virtual member function.

Can we make copy constructor in abstract class?

Yes you should. Rules of having your own implementations for copy constructor, copy assignment operator and destructor for a Class will apply to even an Abstract Class.

What is abstract base class in OOP?

An abstract class is a template definition of methods and variables of a class (category of objects) that contains one or more abstracted methods. Abstract classes are used in all object-oriented programming (OOP) languages, including Java (see Java abstract class), C++, C# and VB.NET.


1 Answers

No, but the copy method does not have to be painful:

class Derived : public Base
{
  public:
    Base *copy() const
    {
        return new Derived(*this);
    }
};

(assuming you already have a copy constructor, which, if you need a deep copy, you'll have).

like image 74
Daniel Gallagher Avatar answered Sep 24 '22 23:09

Daniel Gallagher