Archived

This topic is now archived and is closed to further replies.

BcS

Returning a pointer to an object?

Recommended Posts

I’m a little confused about memory and objects. Let’s say I have a class that defines a data member that’s not a pointer. Let’s say that in some function I create a object from this class using new, so that the object lives on the heap. But where are the data members? On the stack? If they are on the stack, what happens if I return a pointer to this object? Here’s an simple example of what I mean:
#include <iostream>
using namespace std;

class Enemy
{
public:
    Enemy(int health = 100): m_Health(health) {};
    void Status() { cout << "Health: " << m_Health << ".\n"; }
private:
    int m_Health;
};

Enemy* createEnemy()
{
    return (new Enemy);
}

int main()
{
    Enemy* pEnm = createEnemy();
    pEnm->Status();
    return 0;
}
Now, when I run this program with Dev-C++, is runs just fine show the enemy’s health. But should it? I mean isn’t the object’s m_Health a local variable that was on the stack in createEnemy() and shouldn’t have been destroyed once that function ended? Or is the whole object on the heap because I created the object with new? I am confused. Thanks for any help.

Share this post


Link to post
Share on other sites
When you create an object on the heap, it''s members are on the heap. All the functions are only stored in memory once. Classes with virtual member functions have a hidden pointer (a member) that points to a table of virtual function pointers, called the vtbl.

Your program''s fine, except you "leak" the enemy. Since you create it with new, you need to destroy it with delete when you are done with it.

void destroyEnemy(Enemy* p)
{
delete p;
}

int main()
{
Enemy* pEnm = createEnemy();
pEnm->Status();
destroyEnemy(pEnm);
return 0;
}

Share this post


Link to post
Share on other sites
Thanks for the quick reply. Okay, it makes sense that the data members of an object created on the heap are also on the heap.

And yeah, I did forget to delete the object. But I don''t need to write a whole new function for that, do I? I mean I could just do:

delete pEnm;

in main(), right?

Share this post


Link to post
Share on other sites