I have this code in a library:
class Parent
{
//some data and functions
};
void myfunc(Parent& ref);
and I want to do this code in my application:
class Child : public Parent
{
// some other data and functions
void dostuff()
{
myfunc(*this);
}
};
Is it safe to pass *this? (no slicing, no copying, …)
Is it better to call myfunc like this:
myfunc( * ((Parent*)this) )
Note that I don’t have control on what happens inside myfunc, in some cases I don’t even know what happens inside there.
I used passing-parent-by-pointer many times and I am used to it, but have never used passing-parent-by-reference before.
myfunc(*this)is fine, so long asmyfuncis declared to take a reference — which it is.This will not copy the object. It will pass a reference to the original object. Furthermore, it will not slice the object. The reference will be of type
Base&, but the object to which it refers will be unchanged.Just so you know, if you were then to call polymorphic (eg,
virtual) methods on thisBase&, polymorphism will still work right and do what you’d expect — just like if you were to call through a pointer. In other words:…will have the same effect as: