Help with Class and Operator()

Hi guys, I am just starting out with programming, hope you will help me :)

This code returns "hello world 0", but I would like it to return "hello world (and a input)"

What is wrong

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

#include <iostream>

class test
{
public:
	int operator()(int a);
	test();
private:
	int a = 0;
};

test::test()
{
	std::cout << "hello world " << a << std::endl;
};

int test::operator()(int a)
{
	return a;
};

int main() {
	test something;
	something(10);	
	std::cin.get();
};

Let me rewrite the operator for you:
1
2
3
4
int test::operator()(int foo)
{
	return foo;
};

What did change? Nothing. The two programs are identical.


The operator has an argument. In your code the argument has name 'a'.
The argument is an integer variable.

Your class has member variable. Also an integer and also with name 'a'.

The two are not the same. In the body of the function the name 'a' refers to the variable that has been declared in inner scope. The variable of outer scope is masked. Hidden.

The member can still be explicitly referred to via the this pointer:
1
2
3
4
5
void test::bar( int a )
{
  std::cout << a; // function's argument
  std::cout << this->a; // member of class
};

You should avoid identical names, where they cause confusion.


The operator does not touch this->a. It merely returns its argument.


That said, your output statement is in the constructor.
The output occurs as part of evaluating line 24.

Even if your operator() would do something, it would be too late.
thank you Keskiverto.

As mentioned, I am totally new to this stuff.
I don't understand what you are saying :)

could you rewrite the whole code for me, then maybe a can figure out what it means :)
Last edited on
The problem is that a on line 18 'shadows' a on line 10.

In other words: On line 20 you do not return the member variable a (line 10) but the paramter (line 18).

I guess that you want something like this:
1
2
3
4
5
int test::operator()(int a)
{
	this->a = a; // Now the value of the member a is set to the value of the parameter a
	return a;
};
?
Topic archived. No new replies allowed.