K
K
Kalombyr2018-09-10 20:46:57
C++ / C#
Kalombyr, 2018-09-10 20:46:57

How to make chains of calls to methods of one class?

Good afternoon!
I want to make it so that the class methods can be called in a chain, to the perimeter:

MyClass * myClass = new MyClass();
myClass->summ(10).retract(4).div(2).cast(1);
......
......
delete myClass;

Of course, for this it is enough that each method returns an instance of the class, and this is the question - what to return and why?
MyClass &summ(int) {  return *this; }
// ИЛИ
MyClass *summ(int) {  return this; }

As you can see, you can return either a reference or a pointer.
What will be the most correct in this case and why?
PS The copy constructor is rather complicated.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
jcmvbkbc, 2018-09-10
@Kalombyr

you can return either a reference or a pointer.
What will be the most correct in this case and why?

You want to write myClass->summ(10).retract(4).div(2).cast(1);- return the link, you want myClass->summ(10)->retract(4)->div(2)->cast(1);- return the pointer. Otherwise, there is no difference.
It doesn't matter at all if you're not going to return an object instead of a reference or a pointer.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question