Hello project science,
Sorry for the delay. I had some computer problems yesterday and lost track of where I was at.
To start with and what I said eariler:
In the header file you have:
void area(int, int)
In the cpp file you have:
int Math_function::area(int length, int width)
|
So what I did was change the forward declaration in the header file to match the ".cpp" file and when it used
cout << "Area = " << t.area();
it worked because the function call returned a value that "cout" could use.
The error comes from the forward declaration saying that the function is a "void" function, so when the compiler rune it is checking the forward declaration of the class against the function call in the "cout" statement and is thinking that the function returns nothing.
In the error message the last word in the line, "void", is the key to the error.
I believe the class' constructor allows the class public member functions to use the private variables.
|
Not entirely true as
jonnin pointed out. Another way to look at this is that only public member functions of the class can access the private or protected member variables.
The ctor, default or overloaded, have no control over other public member functions. Only the private variables.
Thus, you don't include parameters for the pubic function call as they'd become local variables.
|
Yes and no. It depends on what you are doing. As
jonnin said
1 2 3 4
|
Math_function::Math_function(int L, int W)
{
length = L; width = W;
}
| |
Called an overloaded ctor the variables in the () have different names than the private member variables of the class. The "L" and "W" become local variables to the function, but they are used to set the private member variables. And when you reach the closing } these local variables are destroyed.
Each class only has 1 constructor, and it takes the name of the class name.
|
If not defined each class has 1 default ctor provided by the compiler along with 1 default dtor. Actually a class can have 1 or more overloaded ctors as long as the variables in the () are different. One thing to keep in mind. When you provide an overloaded ctor or dtor the compiler will no longer provide a default. You will have to do the default.
Your revised code works, but the main file is missing the beginning, so I can not see what you have done. So I am guessing that both ".cpp" files should the header file for the class. With out this the code will not compile.
In your function:
1 2 3 4 5
|
void Math_function::area()
{
//cout << "area = " << length * width << endl; // compute area
cout << length * width;
}
| |
Consider:
1 2 3 4
|
int Math_function::area()
{
return length * width;
}
| |
This way you can use the function in a "cout" statement any time you need it. By putting that "cout" in the function it may not print to the screen as you would want without extra work.
I had to add a couple of lines in the ".cpp" files to get the program to work in VS 2017, but it did.
Andy