Pointer undefined even thought it should be

May 30, 2015 at 3:13am
Hello,

I have something like this. Why is lastItem undefined? Is this not the correct syntax?

1
2
3
4
5
6
7
8
9
10
11
Menu*   CreateItem() 
{
    Menu* menuPointer = new Menu;   
    //initialize values     
    return menuPointer; 
}

void AnotherFunction() 
{
    Menu* lastItem = CreateItem();
}


Thanks a lot!
Last edited on May 30, 2015 at 3:13am
May 30, 2015 at 3:34am
No idea. This works for me:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Menu
{
public:
	Menu(){}
	~Menu(){}
};

Menu* CreateMenu()
{
	Menu* menuPointer = new Menu;

	return menuPointer;
}

int main()
{
	Menu* menu = CreateMenu();

	return 0;
}


Maybe show more code?
May 30, 2015 at 3:51am
Thanks for your answer! I just figured it out, but I don't really understand why that wasn't working. The more complete context looks something like 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
25
26
27
28
Menu*   Content::CreateItem() 
{
    Menu* menuPointer = new Menu;   
    //initialize values     
    return menuPointer; 
}

void Content::CreateObject(Menu* curItem, Menu* lastItem)
{
	 lastItem = CreateItem();
	 curItem = lastItem;
}

void Content::Initialize()
{
	Menu*	curItem = 0;
	Menu*	lastItem = 0;

	while (...)
	{
		if (/*object is complete*/)
		{
			CreateObject(curItem, lastItem);
		}
		//create object little by little
	}
}


I changed

1
2
	Menu*	curItem = 0;
	Menu*	lastItem = 0;


to
1
2
	Menu*	curItem = new Menu;
	Menu*	lastItem = new Menu;


Why was this necessary?
May 30, 2015 at 7:22am
no, it still does not work...
look at my last post in this topic: http://www.cplusplus.com/forum/beginner/165851/
May 30, 2015 at 10:58am
OMG, thank you so much! You were right, it only seemed to work but actually did not. It's finally working, thank you very much!
Topic archived. No new replies allowed.