1

Im working on a project where I have a few child classes (Profile1, Profile2, Profile3). One of the functions is to edit the Profile which includes changing type from Profile1 to Profile2. My first idea was to simply delete former object and create new one, however this would require some additional changes in the code and so I've decided to try and find a way where I can keep the pointer to that object but change the value.

This is extremely simplified example of my code:

Parent * currentProfile= new Child1();
Child2* newProfile = new Child2();
*currentProfile = *newProfile;

It works perfectly when I create new object of the same type as the current is, however when I try to assign an object of different type it converts it to the current type (in the example code above the value of object where currentProfile is pointing would change to values of newProfile, however class would remain Child1 instead of Child2).

Is there a simple way of keeping the address but changing type of child Object? If not is there a better way to do this other than deleting previous object and creating new one?

Thank you

2
  • 2
    You cannot change the object type but keep the same address. Different object types require different amounts of memory. Commented Sep 21, 2020 at 10:45
  • Yeah, I see, thanks. Thought it could work somehow since its the same parent class and im always using parent class when creating a pointer Commented Sep 21, 2020 at 10:48

1 Answer 1

1

As I said in comments, you cannot change the object type but keep the same address. Different object types require different amounts of memory

if Child1 and Child2 derive from the same parent, then you could keep the same pointer, but it will hold a different address.

Parent * currentProfile= new Child1();
Child2* newProfile = new Child2();
currentProfile = newProfile;

currentProfile now points at address of Child2.

Sign up to request clarification or add additional context in comments.

1 Comment

Note the above example will leak Child1 memory unless you delete it first or use smart pointers.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.