Okay, so let’s say I have some random abstract base class Base and I have a class Foo which contains a pointer to this base class as a datamember. So
class Foo
{
public:
Foo(Base*);
private:
Base* ptr;
}
Now the reason I use a pointer to the base class is because I want to be able to choose which derived class my Foo object has a pointer to. Now the tricky part is, to me, the implementation of the constructor for Foo.
If I do it like this
Foo::Foo(Base* _ptr)
{
Foo::ptr = _ptr;
};
it would be possible for the user to adjust the object pointed to by Foo::ptr since _ptr will still exist after the constructor has finished. I cannot make the object pointed to by _ptr constant because Foo::ptr needs to update itself regularly. Now I was thinking about adding a line _ptr = NULL at the end of the constructor, but that could be dangerous as well, since the user could try to dereference _ptr.
The only way I can think of to make this work is to make a copy of the object pointed to by _ptr and initializing Foo::ptr to the address of that copy. But then the object pointed to by _ptr would need to have a member function Clone() or something similar because I can’t call the copy constructor for an object of which I don’t know the class at compile-time.
So is there any elegant way of doing this if there is no Clone()? Or is that really the only possibility?
Construct from a
unique_ptr. That way your user has no access to the pointer after it has been used in the creation of aFooobject (unless he really wants to and usesget).e.g.