Generally it appears preferable in C++ that code that functions that take a parameter to a polymorphic object takes a pointer to it:
class Base {};
class DerivedA : public Base {};
class DerivedB : public Base {};
void OperateOnObject(Base* obj) {};
vector<Base*> objects;
objects.push_back(new DerivedA());
objects.push_back(new DerivedB());
for (size_t i=0; i<objects.size(); i++) {
OperateOnObject(objects[i]);
}
Why is it that OperateOnObject() is usually written to take a pointer to Base rather than a reference? Are there potential problems with slicing? (eg the vtable gets lost)
I’ve seen this response to a similar-sounding question, but it doesn’t seem to address the same issue.
References do not present problems with slicing – in this respect, they are as good as pointers. There is no “hard” reason to prefer pointers, unless you want semantics of
NULLto be available to your code (i.e. an ability to pass “nothing”, which is not there if you use references).I think the pointer types are often used as parameters of polymorphic functions to match the semantic of collections: since you cannot make a
vectorof references, your code will end up having to dereference pointers obtained from collections before passing them to functions. This may be annoying.