Answer the question
In order to leave comments, you need to log in
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
Everything is very simple.
The type of a function determines the return value.
For example:
int foo(){
int i = 7666;
return i;
}
void increment(int& i) {
i++;
}
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 questionAsk a Question
731 491 924 answers to any question