AnotherUser
AnotherUser

Reputation: 1353

Instantiating a new instance of a variable

I have two classes. In the main class I have a process that is step by step and can be stepped though, I have implemented this as a state machine. To help keep the machine easy/friendly I created another class that holds information about the current state of the machine. In the main class I then added a reference to it as such

CAnimateMachine *m_AniMach;

After some actions happen I call a function in the main class to instantiate variables within my state machine object. Each call to this function AniInit() should basically "reset" the state machine by instantiating the variables to the "initial state".

My issue is I am not sure how to instantiate my m_AniMach properly. I am used to C# where I can just do

m_AniMach = new CAnimateMachine(); 

to "erase" the old object and instantiate a new one. Though, from what I have read, I can not be so cavalier in C++. What is the proper way to "re-instantiate" this variable in my init method?

Could I use the new operator m_AniMach = new CAnimateMachine() and then in the main class' deconstrutor do delete &m_AniMach?

EDIT: juanchopanza's answer makes sense to me. Though I keep getting an error when trying to compile. I am not exactly sure what the error is trying to tell me, I think it is telling me that my class isn't public when it is? I reviewed the C2248 MSDN article but I do not see how it relates to my situation.

error C2248: 'CObject::operator =' : cannot access private member declared in class 'CObject'
include\afx.h(562) : see declaration of 'CObject::operator ='
include\afx.h(532) : see declaration of 'CObject'
occurred in the compiler generated function 'CAnimateMachine &CAnimateMachine::operator =(const CAnimateMachine &)'

Here is my CAnimateMachine class

class CAnimateMachine
{
public:
    CAnimateMachine();

    int startX,startY;
};

And this is how I instantiate it

m_AniMach = CAnimateMachine();

And how it is defined

CAnimateMachine m_AniMach;

Upvotes: 0

Views: 182

Answers (1)

juanchopanza
juanchopanza

Reputation: 227468

There seems to be no reason to use a pointer. You can use an object instead:

CAnimateMachine m_AniMach;

in which case it will get default initialized when an object of the type that holds it gets instantiated. To "re-initialize" it, you can say

m_AniMach = CAnimateMachine();

If you do this, you will not have to worry about things like following the rule of three or other dynamic allocation pitfalls.

Upvotes: 4

Related Questions