V
V
Veln2020-08-06 13:36:03
C++ / C#
Veln, 2020-08-06 13:36:03

How to choose the return type of a function?

Hello. Please help me understand how to choose the return type of a function? Maybe there are some articles about it or you can explain it yourself. For example, there is a piece of code with the setdata method and I don’t understand why void is written, and not, for example, int

class smallobj // определение класса
{
private:
 int somedata; // поле класса
public:
void setdata(int d) // метод класса, изменяющий значение поля
 { somedata =d; }
void showdata() // метод класса, отображающий значение поля
 { cout << "Значение поля равно " << somedata << endl;}
 };

Answer the question

In order to leave comments, you need to log in

2 answer(s)
T
Ternick, 2020-08-06
@Veln

Everything is very simple.
The type of a function determines the return value.
For example:

int foo(){
    int i = 7666;
    return i;
}

The foo function is of type int because it returns an int value;
There is also a void type, it is used if the function does not return anything, something like this:
void increment(int& i) {
    i++;
}

The increment function takes the address of an int variable as arguments, then increments its value by 1 and returns nothing. so void.
Everything is very simple :)

V
Vladimir Korotenko, 2020-08-06
@firedragon

If a function is in a class and only changes the class, then its type is void. Additionally, you can set an exception when passing incorrect parameters or, for example, a connection break or resource unavailability.
If you need a value right now, then return it.
Static methods are separate. In theory, they should not affect anything at all, except for singleton. But this is a separate case that should be beaten in a particular case.
Summarizing.
Initialize the members in the constructor.
Use properties to access state
Return values ​​only if you need them right now.
Use static methods with return values, and don't rely on the value of the class.
Singleton is a separate case and its use should be carefully considered.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question