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.
// classes example
#include <iostream>
usingnamespace 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;
}
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).
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.