Pass reference of temporary object.

I am currently trying to understand OOP in C++.
I want to know how to pass references of temporary object arguments to functions.
I have an example with 3 ideas of how to do this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
//First idea: Send weapon to init-function.
void Character::send()
{
	init(Weapon cWeapon);
}

//Second idea: Send weapon to init-function.
void Character::send()
{
	Weapon cWeapon;
	init(cWeapon);
}

//Third idea: Send weapon to init-function.
void Character::send()
{
	init(new Weapon);
}

// Assign the characters weapon.
void Character::init(const Weapon& cWeapon)
{
	m_cWeapon = cWeapon;
}


I would prefer the first way to do it if that syntax is legal and if I get what I want. Next option would be the second idea to first create a local object.

I do not like the third idea, since I am using operator 'new' and I do not want to allocate unnecessary memory on the Heap. I only want it to be stored as a global variable in the Global Variables memory section.

What is the correct and best way to achieve this?
Last edited on
I want to know how to pass references of temporary object arguments to functions.


init(Weapon());
Thanks :).
Topic archived. No new replies allowed.