hallo everyone, I am a new user of this forum so I apologize for any mistake.
I am learning C++ programming and during my studying I saw the following example code defining a class:
class CRectangle {
int x, y;
public:
void setValues (int,int);
int area (void);
} rect;
I got that the code define a class CRectangle with on abject called rect.
but I am confused about the following lines:
void setValues (int,int);
int area (void);
My questions are:
- can a function take as argument void?? (see int area (void);)
- does the code "void setValues (int,int);" define a function which takes two in type int parameter as input?
can a function take as argument void?? (see int area (void);)
It just means no input arguments. In C++ don't state the void - int area();
does the code "void setValues (int,int);" define a function which takes two in type int parameter as input?
It declares such a function, yes. The definition of the function is the actual function code, so this does not define such a function. More commonly, they'd be given names - void setValues (int oneValue, int anotherValue);
I know in C++, int myFunc(void); is allowed and I think the reason being is backwards compatibility with C. So as far as standards go, was "void" required when no parameters were specified in C a long time ago? Why do C users do this and why do C++ users not do this?
See the diference between declare e define functions in C/C++. Here's a stub:
1 2 3 4 5 6 7 8 9
// function that sums two numbers
// declaration
int sum (int, int);
// define
int sum (int a, int b)
{
return a + b;
}
See there? In the declaration we only says to copiler: "There's a int returning function that take 2 int's as argument's, witch is defined later".
The "defined later" could be in below or in another header. Yes, you can declare and define the function in only statement too, but the forward declaration is useful for libraries and easily read of your code (you can put the declarations on a .h and definitions on .cpp).