Sign in to follow this  

Turning "new" into a method

This topic is 4555 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

For reasons that are kind of extensive (unless you've been reading my previous posts), I need to create a function that will allow me to pass a class pointer into it and use "new" on it. For example, normally the following would happen: BaseClass* newObject = new InheritedClass(); What I want to do is create a function like this: makeClass(BaseClass* srcClass) { srcClass = new InheritedClass(); } But when I pass the class through that function, it seems to do something radically different and all the contents of the class do not work as they should. Does anyone see what is basically wrong with this code?

Share this post


Link to post
Share on other sites
Well, if that's how you're declaring it then it's not surprising it's not working. You're passing a BaseClass pointer to your function (by value) and then assigning to the function parameter, which is just a temporary copy of your original pointer. When you return from the function you throw that value away and it's lost forever. If you want to pass the pointer in as a reference parameter you need to either pass in a pointer to a pointer or a reference to a pointer. The easier and more common approach would be to have your makeClass function return the pointer instead.


InheritedClass* makeClass()
{
return new InheritedClass();
}

BaseClass* newObject = makeClass();


Share this post


Link to post
Share on other sites

This topic is 4555 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this