I have recently seen a question on stack overflow that how to get derived object from function, some suggested that create local object and return copy from function. how about returning this
from function?
I just wanna know, is that good coding practice?
Thank you for your assistance and time.
below is my example code.
class Base {
public:
virtual ~Base() {}
};
class Derived: public Base
{
private:
int i;
public:
Derived* func(int e) {
i = e;
return this;
}
int getI() { return i; }
};
You could use your code like this
Derived d;
Derived* d_ptr = d.func(123);
Seems easier to just write this (assuming a suitable constructor)
Derived x(123);
Derived* x_ptr = &x;
But maybe you were thinking of something else.
Derived d;
Derived* d_ptr = d.func(123);
why not d_ptr = &d; whey d.func returns this? when use d.func, user have the pointer of d. no need to return again. may be want to use in chain like d.func(1)->func(2)->func(3)
Several operators used to return self reference (but not pointer):
operator +=
, operator -=
, ... mainly to mimic built-in behavior.
That allows to chain operation: a = b = c = 42;
(instead of c = 42; b = c; a = b;
).
(Abusing of) chaining is not necessary more readable, and split in several statements may be clearer.
The pro-chaining also apply it to setter:
rectangle.set_height(42).set_width(21).set_position(x, y);
About pointer versus reference, returning pointer implies generally that nullptr
is possible value (else reference is better).
operators which might return pointer are (address of) operator&
and arrow operator->
.
Behavior of default &
already returns this
, so no need to overload it to return this
.
operator->
should, at the end, returns a pointer; this
might be a valid choice depending of the wrapper class.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.