passing function as a arguement

I read this page about passing function as a arguement on http://www.cplusplus.com/forum/beginner/6596/ and i tried it myself but some error
is popping up and i am unable to run the program.

The code:

inside "TextOperation2.h"

1
2
3
4
5
6
7
8
9
10
11
  #pragma once
class TextOperation2
{
public:
	TextOperation2(void);
	
	bool primeOrNot(int);
	void primesInList(int*,int,bool (*f)(int));

	~TextOperation2(void);
};


inside "TextOperation2.cpp"

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
32
33
34
35
36
#include "stdafx.h"
#include "TextOperation2.h"
using namespace std;

TextOperation2::TextOperation2(void)
{
}


TextOperation2::~TextOperation2(void)
{
}

bool TextOperation2::primeOrNot(int x){
	
	bool porc;
	porc = false;
	for(int i = 2;i<= x/2; i++){
		
		if(x%i == 0){
			porc = true;
			break;
		}
	}
	return porc;

}
void TextOperation2::primesInList(int* nums, int n, bool (*f)(int)){

	bool* p = new bool[n];
	for(int j = 0; j<n; j++){
		p[j] = (*f)(nums[j]);
		cout<<p[j]<<" ,";
	}

}

inside " main cpp file"

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

#include "stdafx.h"
#include "TextOperation2.h"
using namespace std;

TextOperation2 testop;

void main()
{
	fflush(stdout);
	int n ;
	cout <<"enter the number of values u want";
	cin>>n;
	int* list = new int[n];

	cout<<endl<<"enter the list 1"<<endl;
	for ( int counter = 0; counter <n;counter ++)
	{
		cin>>list[counter];
	}
	
	bool boolorn = testop.primeOrNot(n);
	cout<<"\n"<<boolorn;
	testop.primesInList(list,n,&primeOrNot);//i also tried testop.primeOrNot 
	_getch();

}

how can i correct this error ?

I am working under:
Operating system: Windows 7
IDE : Visual Studio 2012

Thanks !


A method is a message passed to an object, if you are not going to use/modify the state of said object, then it should not be a method but a free function.

To clarify, suppose that you were trying to do it in C.
The method bool TextOperation2::primeOrNot(int x)
would become bool primeOrNot(TextOperation2 *this, int x)

note how that's different that the function signature that you are expecting bool foo(int)


> some error is popping up and i am unable to run the program.
¿don't you think that the error message would be important?
If you could not understand what was trying to tell you, then that's more a reason to post it so we could read it
Last edited on
ohh yes , though i had to read again and again, but i got it.Thank!
I simple dont need the function as the arguement and
changing
 
p[j] = TextOperation2::primeOrNot(nums[j]);


does the job!
Thanks again!
Topic archived. No new replies allowed.