Hi there, I am very new to C++, so this is probably a really stupid beginners mistake, but yet I cant figure it out on my own. The following program should print 5 to the screen, but instead it gives me something like -89187987. I am puzzled
#include<iostream>
usingnamespace std;
class test
{
private:
int a, b;
public:
test(int a);
double made();
};
test::test(int a)
{
a = a;
}
double test::made()
{
b = a;
return b;
}
int main()
{
test testexample(5);
cout<<"b is: "<<testexample.made()<<endl;
return 0;
}
In the test constructor you're assigning the parameter a to itself, so that has no effect. The class member remains uninitialized.
There are three ways to fix this:
1. The proper way: you should use the initializer list to initialize any class members:
1 2 3
test::test(int a) : a(a)
{
}
2. give the parameter a different name, such as a_.
3. Explicitly refer to the class member with this->a=a;
What happens is the parameter variable 'hides' any other variable of the same name in the class scope. So if you want to refer to the class member variable 'a' you need to explicitely specify it as this->a
1 2 3 4
test::test(int a)
{
this->a = a;
}
As Athar pointed out the best way to initialise member variables is in the ctor-initializer:
1 2 3
test::test(int a) : a(a) // not ambiguous
{
}
The reason why that works is because the compiler can tell the difference between the two 'a' variables. The one outside the parentheses must belong to the class and the one in the parentheses is whatever is least hidden in the scope (in this case the parameter).
Thank you guys. I see now what happens. Would it be "unprofessional" to put
test(int _a) instead of test(int a)
to give it a different name? Of course, this example is reduced to the actual problem, in my real code I have several imput variables for the function "test" how does the ctor-initializer work in this case?
It would not be unprofessional, however you in general should not use variable names (or
identifiers in general) that begin with an underscore, as those are reserved for use by
compiler writers.