What is wrong with my program?

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include<iostream>
using namespace 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;
}
Last edited on
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;
Last edited on
Yes, indeed, your line 16:

 
	a = a;


What did you expect that to do?


In situations like this:

1
2
3
4
test::test(int a)
{
	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?
Many people use a naming convention to differentiate class member variables or parameter variables.

The ctor-initialization of a class member variable has the general form class_variable(value).

So in your example:

1
2
3
4
5
6
7
8
class test
{
private:
    int a;

public:
    test(int _a) : a(_a) {} // a is the class member, _a is the value.


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.
Topic archived. No new replies allowed.