Why is this declared void?

Hi guys.

I'm going through the (really good) tutorials on here and a bit confused at one point. Mainly, in the class CRectangle, why is set_values declared void?

I've commented the program as far as I understand it - feel free to correct me to improve my understanding.

Many thanks
JS

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// classes example
#include <iostream>
using namespace std;

class CRectangle {                  // new class called CRectangle
      int x, y;                     // private member variables, x and y
      public:                                  //public member variables
             void set_values (int,int);        //void ??
             int area() {return (x*y);}        //int area returns value x*y ??
};

void CRectangle::set_values (int a, int b) {   //the set_values member is defined outside the class
     x=a;                   //as x=a
     y=b;                   //and b=y
}

int main()
{
    CRectangle rect;                 //declare new object from class CRectangle
    rect.set_values (3,4);           //set_values member is declared here
    cout << "area: " << rect.area(); //public member variable area is output here.
    return 0;
  
}
... because it doesn't return a value. It changes the state of CRectangle.
kbw wrote:
because it doesn't return a value
As kbw said, the return type is void as it does not return anything.

The variable type that precedes a function/method prototype defines the type of variable/object that will be returned by it.

You can find documentation about this here: http://www.cplusplus.com/doc/tutorial/functions/ .

There is a nice section at the bottom of the above link that deals with your query.

I hope this helps.
Last edited on
This is somewhat of a stupid example isn't it? set_values is doing what a constructor should do, so why didn't they make a constructor instead?
This is somewhat of a stupid example isn't it?
You're calling tutorial code stupid?
ascii, unless you intend to create a new object every time you want to change its value, there is some value to that function.

-Albatross
Last edited on
Well yes, but there's only one object here. I do see your point that it could be useful in a longer program however :)

And while the person who wrote the tutorial on this website is certainly a far better C++ programmer than me, yes I am saying that in this example I think a constructor would have been the better way to go. But I'm also unaware of the context (e.g. if the writer wanted to introduce constructors later).
Last edited on
The point is that the program is there to illustrate something. The existence of this thread is testimony to the usefulness of that. I really don't think it's stupid.
Topic archived. No new replies allowed.