I want to create a function in C++ to get a pointer to a class with some conditions. I have multiples instances for a class, identified by a number. Depending on number, I want to get the corresponding instance.
In c# it would be something like :
class main
{
private Example item1;
private Example item2;
private Example item3;
private Example item4;
public bool InitializeItem(int itemID)
{
bool isInitialized = false;
Example item;
if (tryGetItem(itemID, out item))
{
item = new Example(itemID);
isInitialized = true;
}
return isInitialized;
}
private bool tryGetItem(int itemID, out Example item)
{
bool canGet = false;
item = null;
switch (itemID)
{
case 1:
item = item1;
canGet = true;
break;
case 2:
item = item2;
canGet = true;
break;
case 3:
item = item3;
canGet = true;
break;
case 4:
item = item4;
canGet = true;
break;
}
return canGet;
}
}
class Example
{
int number { get; set; }
public Example(int i)
{
number = i;
}
}
But in C++ I'm a little bit confuse with referencing and pointers. I read some tutorials like this one(in french). I understood basic pointers but with classes and function i'm lost.
With first answer, I changed my code to :
Example item1;
Example item2;
Example item3;
Example item4;
bool tryGetItem(int b, Example &ptr)
{
bool canGet = false;
ptr = NULL;
switch (b)
{
case 1:
ptr = item1;
canGet = true;
break;
/* etc */
}
return canGet;
}
bool InitializeItem(int id)
{
bool isInit = false;
Example ptr = NULL;
if (getParam(id, ptr))
{
ptr = Example(id);
isInit = true;
}
return isInit;
}
But it doesn't work. I've try to debug, getParam(1, ptr)
is true, in the {..} the variable ptr
is correctly set to 1 but item1
doesn't change.
Edit:
I don't think it's the same problem that possible duplicate post. I don't want to modify ptr
in tryGetItem
, I want to use tryGetItem
to make ptr
pointing on one of my itemX
. After using tryGetItem
with value 1, modifying ptr
must modify item1
too.