Void Functions

Hey Guys

can someone please explain the purpose of void functions, how to use them and when is the best time to apply void functions.

Thanks Guys
closed account (S6k9GNh0)
Well, when the time comes it should be obvious. It's useful in classes for set function:

1
2
3
4
5
6
7
class bob
{
   private: 
      int myInt;
   public:
      void setMyInt(int newNumber);
}


It can also be used when your using references to change a variable.

1
2
3
4
void aFunction(int &myInt)
{
   myInt = anotherInt; //This is sometimes more effecient than having a return value at all.
}


To be honest, this is a matter of just thinking about. Plus, like I said, when you need a void function, you'll know.
Each function that doesn't need to return a value should be void

eg:

1
2
3
4
void DisplayHelloWorld()
{
    std::cout << "Hello World!";
}
a void function does not need an input, or return value.
closed account (S6k9GNh0)
Usually the point in the function is gone when it has no return or parameter.
quote from computerquip:

1
2
3
4
void aFunction(int &myInt)
{
   myInt = anotherInt; //This is sometimes more effecient than having a return value at all.
}


ehhhh. I wouldn't advise code like this.

I actually see a lot of people in the newbie board passing int& as parameters. I suspect this is because people spout out "passing by reference is more efficient". Granted you didn't say that here (or at least you qualified it with "sometimes"), but I felt like chiming in anyway.


Function formats like this can get in the way of compiler optimizations and make your code harder to read and maintain. Plus they make the function harder to use because you can't put it as part of another statement:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class MyClass
{
public:
  int get() { return anotherInt; }
  void fakeget(int& v) { v = anotherInt; }

protected:
  int anotherInt;
};

void func()
{
  MyClass a, b;

  int foo = a.get() + b.get();  // easy 1 liner, AND [likely] more efficient

  int bar, bar2;
  a.fakeget(bar);
  b.fakeget(bar2);
  bar += bar2;             // not as easy 4 liner, [likely] less efficient
}


Now if you're talking about large objects like classes, where copying the object is expensive -- then yeah, passing by reference might be the way to go. Or, of course, if you need to "get" more than one variable, then passing by reference is pretty much necessary.

Anyway blah

</anal>
Topic archived. No new replies allowed.