Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

new operator in function parameter

I have a function and that function takes in a class pointer. the problem is that I call the class pointer like this.

Function (new ChildClass);

the function looks something like this

void Function (BaseClass *instance)
{
    childClassInstance = instance;
}

the reason why I call it with the new keyword is because I need it outside my function. What I wanted to know was. When I'm ready to delete instance. How would I go about it? Since it's in the function parameter, how would I go about calling it in order to delete it? or how would I be able to access it's location in memory to be able to delete it?

If this is not possible what would be a better solution?

like image 515
user1583115 Avatar asked Sep 05 '25 03:09

user1583115


1 Answers

You can declare a variable to store your pointer before you call your function. Then you can delete it after your function returns.

ChildClass *c = new ChildClass;
Function(c);
delete c;

But, if this is your idiom, then just use an automatic instance. Then, when it falls out of scope, your object is deleted automatically.

ChildClass c;
Function(&c);
like image 167
jxh Avatar answered Sep 07 '25 23:09

jxh