why cannot convert parameter 1 from 'ICommand *' to 'ICommand *&'?

i can not pass a pointer to ICommand to a Test(ICommand * &p), and why got this error? thx!

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
#include <list>

class ICommand{public : virtual void vfunc(){}};
class CSession : public ICommand{};

void Test(ICommand * & pCommand){delete pCommand; pCommand = NULL;}

int main(int argc, char *argv[])
{
	ICommand * pCommand = new ICommand();
	CSession * pSession = new CSession();

	std::list<ICommand*> commands;	commands.push_back(pCommand);
	std::list<CSession*> sessions;	sessions.push_back(pSession);

	Test(*commands.begin());

	ICommand *p = dynamic_cast<ICommand*>(*sessions.begin());
	Test(p);

	sessions.push_back(new CSession());

	Test(dynamic_cast<ICommand*>(*sessions.begin())); // cannot convert parameter 1 from 'ICommand *' to 'ICommand *&'

	return 0;
}
Last edited on
For a temporary object const reference is required.
a const reference ? but there is no one parameter is const.
I am repeating the second time: for a temporary object const reference required.

Here

Test(dynamic_cast<ICommand*>(*sessions.begin()));

the argument is a temporary object.
sorry, i can't understand what u say, could u show ur code that's correctly?
Test() takes a reference, but you are passing it a temporary variable; specifically, the result of your dynamic_cast. This isn't allowed. You need to make Test() take a const reference, or first assign the dynamic_cast result to a variable before passing it to Test().
i see, Thank you vlan, Thank you Zhuge!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>

int GetInt(){ return 200; }

void Test(int & a){ a = 100; }

int main(int argc, char *argv[])
{
	int i = GetInt();

	Test(i); // works

	//Test(GetInt());	// cannot convert parameter 1 from 'int' to 'int &'

	return 0;
}
Exactly. Good to see you understand. :)
Topic archived. No new replies allowed.