So I want to override the pure abstract method in my derived classes but I got this error. Can someone help me see what happened and how can I complete it.
My Device class;
class Device {
public:
Device();
Device(const Device& orig);
virtual ~Device();
virtual Device Clone() = 0;
}
And my derived class;
class Radar : public Device {
public:
Radar();
// Radar(const Radar& orig); // commenting so the compiler using its default copy constructor
virtual ~Radar();
Radar Clone();
};
Source file for my Radar class;
Radar Radar::Clone() {
return *(new Radar(*this));
}
If I use Device type in my Clone method in Device class, it will pop-up that Device is an abstract class.
If I use void type (which I'm assuming it's not what I want to have), it will show that I haven't implement this method.
What should I do?
Your Clone method will need to return pointers to the cloned objects... covariant return types only work that way (as returning by value is asking the caller to copy the returned value to the stack - that would be a memory leak when you've allocated it with new).
So, it should be:
virtual Device* Clone() = 0;
...and later...
Radar* Clone(); // YES, it should be Radar* here - that uses C++'s support for
// "covariant return types", see also "UPDATE" discussion
Radar* Radar::Clone()
{
return new Radar(*this);
}
UPDATE - further explanation as requested
So, the idea with a clone function is that it can return a deep copy of whatever actual derived type your Device* is currently addressing. Given that derived type might add data members that Device lacked, it could be a larger object, and the caller has no ability to reserve the right amount of stack space in which to store it. For that reason, the object needs to be allocated dynamically with new, and the predictably-sized Device* is the caller's way to access the new object. It's legal for the clone function to return a Radar* though - all that means is that client code that knows at compile time that it is dealing with a Radar and clones it can continue to use it as a Radar - accessing any extra members that Radar provides.
Hope that helps clarify things. You might also want to do some background reading on Object Oriented programming.
A classic approach to implementing this cloning technique is to use covariant return types for the Clone() method. Coupled with modern RAII techniques (e.g. unique_ptr et. al.) it offers a very flexible and safe combination to manage and clone the objects appropriately.
One of the advantages of the covariant return type is that you are able to obtain a clone an object (a deep copy) and the return type is at the same level in the hierarchy as the argument (i.e. the return is not always to the base class) and no immediate casting is required. In C++, pointers and references support covariance, values do not support covariance.
Using a smart pointer such as unique_ptr is advised over raw painters to avoid memory leaks. The clone_unique factory is modelled on the corresponding make_unique utility from the standard library and returns a unique_ptr. It contains explicit type checks on the class hierarchy of the argument and target types.
The solution does require use of std::unique_ptr. If not available with your compiler, boost provides alternatives for these. There are a few other newer C++ language features, but these can be removed if required.
#include <type_traits>
#include <utility>
#include <memory>
class Device {
public:
virtual Device* Clone() const = 0;
};
class Radar : public Device {
public:
virtual Radar* Clone() const override {
// ^^^^^^ covariant return compared to Device::Clone
return new Radar(*this);
}
};
// Clone factory
template <typename Class, typename T>
std::unique_ptr<Class> clone_unique(T&& source)
{
static_assert(std::is_base_of<Class, typename std::decay<decltype(*source)>::type>::value,
"can only clone for pointers to the target type (or base thereof)");
return std::unique_ptr<Class>(source->Clone());
}
int main()
{
std::unique_ptr<Radar> radar(new Radar());
std::unique_ptr<Device> cloned = clone_unique<Device>(radar);
}
Sample code.
See this related answer for a longer example.
Please try the following signature
virtual Device& Clone() = 0;
or
virtual Device* Clone() = 0;
//Body
Device& Radar::Clone() {
return Radar(*this));
}
Related
So let's say I have some ABC in C++:
struct IRun {
virtual ~IRun() {}
virtual void run() =0;
};
And I have another class that I want to be provided an instance of this interface to work with:
struct Other {
IRun* runner_;
};
The issue is that I have to hold runner_ as a pointer to get virtual dispatch (references are out as they aren't assignable). I'd like to be "modern" in my usage, so runner_ probably belongs in a smart pointer.
I'd like Other to be copyable and not share state, so shared_ptr and unique_ptr are out. The only option I can see is writing my own that copies the underlying object via a clone() virtual function? Is there anything in standard C++ (<= C++11) that's meant for this use case?
That is correct, there is nothing built-in in C++ to do this.
You will have to create a clone() virtual function that creates a copy, and implement it in each subclass of IRun.
From the boost library documentation I read this:
Conceptually, smart pointers are seen as owning the object pointed to,
and thus responsible for deletion of the object when it is no longer
needed.
I have a very simple problem: I want to use RAII for pointer attributes of a class that is Copyable and Assignable.
The copy and assignment operations should be deep: every object should have its own copy of the actual data. Also, RTTI needs to be available for the attributes (their type may also be determined at runtime).
Should I be searching for an implementation of a Copyable smart pointer (the data are small, so I don't need Copy on Write pointers), or do I delegate the copy operation to the copy constructors of my objects as shown in this answer?
Which smart pointer do I choose for simple RAII of a class that is copyable and assignable? (I'm thinking that the unique_ptr with delegated copy/assignment operations to the class copy constructor and assignment operator would make a proper choice, but I am not sure)
Here's a pseudocode for the problem using raw pointers, it's just a problem description, not a running C++ code:
// Operation interface
class ModelOperation
{
public:
virtual void operate = ();
};
// Implementation of an operation called Special
class SpecialModelOperation
:
public ModelOperation
{
private:
// Private attributes are present here in a real implementation.
public:
// Implement operation
void operate () {};
};
// All operations conform to ModelOperation interface
// These are possible operation names:
// class MoreSpecialOperation;
// class DifferentOperation;
// Concrete model with different operations
class MyModel
{
private:
ModelOperation* firstOperation_;
ModelOperation* secondOperation_;
public:
MyModel()
:
firstOperation_(0),
secondOperation_(0)
{
// Forgetting about run-time type definition from input files here.
firstOperation_ = new MoreSpecialOperation();
secondOperation_ = new DifferentOperation();
}
void operate()
{
firstOperation_->operate();
secondOperation_->operate();
}
~MyModel()
{
delete firstOperation_;
firstOperation_ = 0;
delete secondOperation_;
secondOperation_ = 0;
}
};
int main()
{
MyModel modelOne;
// Some internal scope
{
// I want modelTwo to have its own set of copied, not referenced
// operations, and at the same time I need RAII to for the operations,
// deleting them automatically as soon as it goes out of scope.
// This saves me from writing destructors for different concrete models.
MyModel modelTwo (modelOne);
}
return 0;
}
If you accept some requirements on your types, this can be done without requiring implementing virtual clone functions for all types. The particular requirements are that the types have accessible copy constructors, which some would deem undesirable because of potential for accidental slicing. Proper use of friending may mitigate the drawbacks of that, though.
If such is acceptable one can go about this by erasing the derived types under an interface that provides copy functionality:
template <typename Base>
struct clonable {
// virtual copy
// this clone function will be generated via templates
// no boilerplate is involved
virtual std::unique_ptr<clonable<Base>> clone() const = 0;
// expose the actual data
virtual Base* get() = 0;
virtual Base const* get() const = 0;
// virtual destructor
// note that this also obviates the need for a virtual destructor on Base
// I would probably still make it virtual, though, just in case
virtual ~clonable() = default;
};
This interface is implemented by a class templated on the most derived type, and thus knows how to make normal copies through the copy constructor.
template <typename Base, typename Derived>
struct clonable_holder : clonable<Base> {
// I suppose other constructors could be provided
// like a forwarding one for emplacing, but I am going for minimal here
clonable_holder(Derived value)
: storage(std::move(value)) {}
// here we know the most derived type, so we can use the copy constructor
// without risk of slicing
std::unique_ptr<clonable<Base>> clone() const override {
return std::unique_ptr<clonable<Base>>(new clonable_holder(storage));
}
Base* get() override { return &storage; }
Base const* get() const override { return &storage; }
private:
Derived storage;
};
This will generate virtual copy functions for us without extra boilerplate. Now we can build a smart pointer-like class on top of this (not quite a smart pointer because it does not give pointer semantics, but value semantics instead).
template <typename Base>
struct polymorphic_value {
// this constructor captures the most derived type and erases it
// this is a point where slicing may still occur
// so making it explicit may be desirable
// we could force constructions through a forwarding factory class for extra safety
template <typename Derived>
polymorphic_value(Derived value)
: handle(new clonable_holder<Base, Derived>(std::move(value))) {
static_assert(std::is_base_of<Base, Derived>::value,
"value must be derived from Base");
}
// moving is free thanks to unique_ptr
polymorphic_value(polymorphic_value&&) = default;
polymorphic_value& operator=(polymorphic_value&&) = default;
// copying uses our virtual interface
polymorphic_value(polymorphic_value const& that)
: handle(that.handle->clone()) {}
polymorphic_value& operator=(polymorphic_value const& that) {
handle = that.handle->clone();
return *this;
}
// other useful constructors involve upcasting and so on
// and then useful stuff for actually using the value
Base* operator->() { return handle.get(); }
Base const* operator->() const { return handle.get(); }
// ...
private:
std::unique_ptr<clonable<Base>> handle;
};
This is just a minimal interface, but it can easily be fleshed out from here to cover more usage scenarios.
It's a bit late, but for future viewers: There's a ready-to-use implementation in my header-only library Aurora and its SmartPtr tutorial. With Aurora, it's trivial to implement deep-copy through smart pointers. The following code works for any copyable type T:
aurora::CopiedPtr<T> first(new T);
aurora::CopiedPtr<T> second = first; // deep copy
This makes it often unnecessary to implement The Big Three/Five if your classes have pointer members.
It sounds like need to be able to make a smart pointer that creates a new copy of the object each time another smart pointer object is created. (Whether that copy is "deep" or not is up to the constructor of the object, I guess; the objects you're storing could have many levels deep of ownership, for all we know, so "deep" depends on the meaning of the objects. The main thing for our purposes is that you want something that creates a distinct object when the smart pointer is constructed with a reference from another one, rather than just taking out a pointer to the existing object.)
If I've understood the question correctly, then you will require a virtual clone method. There's no other way to call the derived class's constructor correctly.
struct Clonable {
virtual ~Clonable() {}
virtual Clonable* clone() = 0;
};
struct AutoPtrClonable {
AutoPtrClonable(Clonable* cl=0) : obj(cl) { }
AutoPtrClonable(const AutoPtrClonable& apc) : obj(apc.obj->clone()) { }
~AutoPtrClonable() { delete obj; }
// operator->, operator*, etc
Clonable* obj;
};
To use sample code, make it into a template, etc.
I've never heard about ready-to-use realisation, but you can simply do it by yourself.
First of all your should write some template wrapper class which has virtual clone method, returning copy of stored object. And then write some polymophic holder of that class which would be copyable
and don't forget about checked delete
http://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Checked_delete
You have two solutions ( actually you have many more, but these make most sense to me :) ):
First, you can use std::unique_ptr. This is a good solution because it forces you to have one instance per pointer. (using std::shared_ptr instead would work as well, but if you do not add the code explicitely, copy and assignment for shared_ptr will "share" - especially what you want to avoid).
If you use std::unique_ptr, your copy constructor and assignment operator should explicitly deep-copy (using either a virtual clone method in the pointee's interface, or new operator in the call to the unique_ptr constructor).
Second, you can roll your own. There's nothing complicated about it, and we're talking about a small (10-20 lines or so) utility class.
Personally, if I had to use this smart pointer class in one place, I would use std::unique_ptr. Otherwise (multiple pointers, same behavior) I would roll my own, simply so I wouldn't have to repeat the deep copy for many instances (to keep with the DRY principle).
I recently found an example of using static member functions in pure abstract classes to initialize pointers to objects of its derived classes.
I was wondering, if it's a design pattern or if it's a good programming practice? The code below is only an ilustration (e.g. both the defineRectangle() and defineCircle() member
functions):
class Shape;
typedef std::unique_ptr<Shape> shape_ptr;
class Shape{
public:
Shape(){};
virtual ~Shape(){};
virtual void draw() const = 0;
virtual float area() const = 0;
virtual shape_ptr clone() const = 0;
virtual shape_ptr create() const = 0;
static shape_ptr defineRectangle(int, int );
static shape_ptr defineCircle(float);
};
shape_ptr Shape::defineRectangle(int height, int width){
shape_ptr ptrRectangle = shape_ptr(new Rectangle(height, width));
return (ptrRectangle);
}
shape_ptr Shape::defineCircle(float radius){
shape_ptr ptrCircle = shape_ptr(new Circle(radius));
return (ptrCircle);
}
The final goal is to define a container of derived classes. For instance:
std::vector<std::unique_ptr<Shape> > vect;
and then we could add the derived classes in the container by either calling the static member functions of the Shape class:
vect.push_back(Shape::defineCircle(10));
vect.push_back(Shape::defineRectangle(5, 4));
or directly without any interface:
vect.push_back(std::unique_ptr<Shape>(new Circle(10)));
vect.push_back(std::unique_ptr<Shape>(new Rectangle(5,4)));
Which of both two ways of adding a derived class in a container should be preferred and why?
The full code can be found in the following link.
Any lights on it are really welcomed ;-)
I was wondering, if it's a design pattern or if it's a good programming practice?
Yes, it's a variation on the factory pattern.
Basically put, it allows you to have a single method, that depending on the arguments to that method, will dispatch the dynamic creation of the correct derived object type. This allows you to use the same "factory" function in your code, and if there are any changes or additions to the underlying objects that the factory method creates, you do not have to change the code that is actually calling your "factory" function. Thus it's a form of encapsulation that isolates any changes for object creation to the segment of the code that is behind the "factory", not the code calling the "factory". For instance, using a factory, it's relatively trivial to add new types that the factory-method can create, but none of the previous code that is making a call to the factory has to change. You merely need to create a new derived class for the new object you want to create, and for any new code that desires that new object, you pass the correct new arguments. All the old arguments still work, and there are not changes that need to take place in the code with regards to returned pointer-types, etc.
The reason for using smart-pointers with the factory is to avoid memory leaks that can occur when pointer-ownership is ambiguous. For instance the factory has to return a pointer since it is dyanmically creating the object. The question then becomes who cleans up the pointer in order to avoid either dangling pointers or memory leaks? Smart pointers clear up this ownership problem, and guarantee that memory is not either inadvertently cleaned up when other objects are still pointing to that memory, or that the memory is not simply lost because the last pointer to that memory location goes out of scope without having delete called on it.
I'd advise against putting factory methods in the base class because, technically, Shape knows nothing about Rectangle or Circle. If you add a new shape, such as Donut, then what will you do? Add a new factory method to Shape? You'll clutter the interface in no time. So, IMO, the second method would be better.
If you want to reduce the verbosity of having to create shape_ptr a every time, you could always move the factory methods to the appropriate subclass:
class Circle : public Shape
{
// ...
public:
static shape_ptr make(float radius)
{
return shape_ptr(new Circle(radius));
}
};
// ...
vect.push_back(Circle::make(5.0f));
Since there is std::unique_ptr, I assume the compiler supports C++11. In that case, let me offer the third option:
vect.emplace_back(new Circle(10));
vect.emplace_back(new Rectangle(5,4));
(About .emplace_back: push_back vs emplace_back)
With this you don't need to repeat the shape_ptr, and you don't need to declare a new factory method to Shape whenever you add a new subclass.
Edit: In C++14, you can use std::make_unique to get rid of the raw new call.
vect.emplace_back(std::make_unique<Circle>(10));
vect.emplace_back(std::make_unique<Rectangle>(5, 4));
If I want to clone a polymorphic object in C++ (i.e. an instance of a class A which is derived from some other class B), the easiest way seems to give B a virtual clone member function, that has to be overridden by A and looks like this
A* clone(){
return new A(*this);
}
My problem is, that I find this unnecessary boilerplate code, as this is almost always needed, if one wants to use run-time polymorphic features of C++. How can it be circumvented?
Thanks
Why I need this:
My use case can be abstracted to the following example:
I have a class Integral, which evaluates the integral of some function. Do do this, they have a member which is a pointer to the class MathFunction. This abstract class contains a pure virtual function evaluate which takes one argument. I I wanted to implement the power function I would create a class PowFunction : class MathFunction. This class would have a member exponent and the function evaluate would look like this:
double evaluate(x){
return pow(x,exponent);
}
As stated the member MathFunction of class Integral has to be polymorhpic, which requires it to be a pointer. To answer the questions of the commenters with another question. Why wouldn't I want to be able to make copies of MathFunction objects?
I really want the Integral to "own" its MathFunction, meaning, that it can alter the parameters (like exponent) without changing the MathFunction of any other Integral object. This means every Integral needs to have its own copy. This requires a clone() function for MathFunctions, doesn't it?
One alternative i thought of: If several Integral objects can share the same MathFunction via a pointer to the same address, I could create copies of Integral objects without the need to copy the MathFunction. But in this case I would have to make all the properties const or somehow readonly, which is not very elegant either. Also, which Integral object should handle delete the MathFunction object?
Why you need this:
Are you seriously saying, that as soon as you work with polymorphic objects you don't ever need a copy operation? What makes polymorphic object different from other objects in this respect?
Using this argumentation, you could also throw the copy constructor and copy assignment operator out of the C++ standard!
Reduce the need to clone polymorphic objects. Really, I rarely find the need for this in my own code, and the comments on the question suggest that I'm hardly alone in the opinion that if you find yourself cloning everything, you're probably designing it wrong.
Of course, never to be unhelpful, you could indeed use the Curiously Recurring Template Pattern.
template<typename T> struct Clone {
virtual T* clone() { return new T(static_cast<const T&>(*this)); }
};
I handled this issue with a macro... it's ugly, but it works to avoid inconsistencies.
/** An interface that can be inherited by any class that wants to provide a Clone()
* method that will return a copy of itself.
*/
class ICloneable
{
public:
ICloneable() {}
virtual ~ICloneable() {}
virtual ICloneable * Clone() const = 0;
};
#define DECLARE_STANDARD_CLONE_METHOD(class_name) virtual ICloneable * Clone() const {new class_name(*this);}
[...]
public MyCloneableClass : public ICloneable
{
public:
MyCloneableClass() {}
DECLARE_STANDARD_CLONE_METHOD(MyCloneableClass);
};
I'm experiencing a challenging problem, which has not been solvable - hopefully until now. I'm developing my own framework and therefore trying to offer the user flexibility with all the code complexity under the hood.
First of all I have an abstract base class which users can implement, obviously simplified:
class IStateTransit
{
public:
bool ConnectionPossible(void) = 0;
}
// A user defines their own class like so
class MyStateTransit : public IStateTransit
{
public:
bool ConnectionPossible(void){ return true; }
}
Next, I define a factory class. Users can register their own custom state transit objects and refer to them later by simply using a string identifier they have chosen:
class TransitFactory : public Singleton<TransitFactory>
{
public:
template<typename T> void RegisterStateTransit(const string& name)
{
// If the transit type is not already registered, add it.
if(transits.find(name) == transits.end())
{
transits.insert(pair<string, IStateTransit*>(name, new T()));
};
}
IStateTransit* TransitFactory::GetStateTransit(const string& type) const
{
return transits.find(type)->second;
};
private:
map<string, IStateTransit*> transits;
}
Now the problem is (probably obviously) that whenever a user requests a transit by calling GetStateTransit the system currently keeps returning the same object - a pointer to the same object that is. I want to change this.
PROBLEM: How can I return a new (clone) of the original IStateTransit object without the user having to define their own copy constructor or virtual constructor. Ideally I would somehow like the GetStateTransit method to be able to cast the IStateTransit object down to the derived type it is at runtime and return a clone of that instance. The biggest hurdle is that I do not want the user to have to implement any extra (and probably complex) methods.
4 hours of Googling and trying has led me nowhere. The one who has the answer is a hero!
The problem is that you don't have the type information to perform the clone as you only have a pointer to base class type and no knowledge as to what derived types have been implemented and are available.
I think there's a reason that 4 hours of googling haven't turned anything up. If you want IStateTransit to be cloneable you have to have an interface where the derived class implementer provides some sort of clone method implementation.
I'm sorry if this isn't what you wanted to hear.
However, implementing a clone method shouldn't be a big burden. Only the class implementor knows how a class can be copied, given a correct copy constructor, clone can be implemented for a leaf-node class like this:
Base* clone() const
{
return new MyType(*this);
}
You could even macro-alize it; although I wouldn't.
If I understand the problem correctly, you shouldn't insert new T -s into the map, but rather objects that create new T-s.
struct ICreateTransit
{
virtual ~ICreateTransit() {}
virtual IStateTransite* create() const = 0;
};
template <class T>
struct CreateTransit: public ICreateTransit
{
virtual IStateTransit* create() const { return new T(); }
};
And now insert:
transits.insert(pair<string, ICreateTransit*>(name, new CreateTransit<T>()));
And retrieve "copies" with:
return transits.find(type)->second->create(); //hopefully with error handling
It shouldn't be impossible to modify StateTransit<T> so it holds a T of which to make copies of, should the default one not do.
I think the general name for techniques like this is called "type erasure" (derived types "remember" particular types, although the base class is unaware of those).
This problem to me sounds that the abstract factory pattern might be of help. Using this pattern the libraries client can define how your framework builds its types. The client can inject his own subclass of the factory into the framework and define there what types should be build.
What you need is (additionaly)
A base class for the factory
As a client: Derive a concrete factory
A way to inject (as a client) a subtype of the factory into the framework
Call the factory metods to create new types.
Does this help you?