Polymorphism in C++

Started by
2 comments, last by graveyard filla 19 years, 4 months ago
Lets say you have 2 classes calles CMap1 and CMap2. They both inherit from CGameMap. So, you declare a pointer like this. CGameMap* theMap = 0; Somewhere later in your code, you point theMap at a Map1 Object.. theMap = new CMap1(); Later, you point it at a CMap2 object... theMap = new CMap2(); Is the pointer still pointing to the same memory? Is the object of CMap1 destroyed? I know it doesn't call any destructors when it switches because I put output in the destructor and never saw it called. Is there any other concerns I should be aware of when using polymorphisim this way? I am just learning this concept, so any help or suggestions are greatly appreciated.
Marriage is the #1 cause of divorce
Advertisement
well, it does not pointing to the same space in memory. when you call new, a new space in memory is allocated for a CMap2 object, and the pointer points to it, so you loose track of the first object, of type CMap1. if you don't have another pointer to it, and there is no garbage collection, that is bad programming, because the space will not be freed until you restart your computer. you must deallocate everything that you allocate.
Quote:
Is the pointer still pointing to the same memory?


No. It's now pointing to the memory you've allocated in creating cmap2.

Quote:
Is the object of CMap1 destroyed?


No. It's only destroyed when you call delete (or delete [] for arrays). You've got a classic example of a memory leak, where you've newed memory (for cmap1) and removed the pointer from it - the memory is still there, but you can't get to it to delete it!

Quote:
I know it doesn't call any destructors when it switches because I put output in the destructor and never saw it called.


Because it's not being destroyed - see above. If you do:

theMap = new CMap1();delete theMap;theMap = new CMap2();


With this you'll get the destructor call.

Quote:
Is there any other concerns I should be aware of when using polymorphisim this way?


Yeah, there's quite a lot. For starters (and bear in mind this is only the tip of the iceberg), you might want to look up 'Smart Pointers' (and the Boost libraries) and the STL, so you can store multiple instances of cGameMap.

HTH,
Jim.
by the way, is this a real world example? i hope your not really making a new MapX class for each map you have [smile]. however, it could fit your situation, but it just jumped out at me. maybe explain what your doing and me or someone else could offer an alternative design (if appropriate)?
FTA, my 2D futuristic action MMORPG

This topic is closed to new replies.

Advertisement