You can't delete the object unless you have a pointer (or reference) to it.
Normally, when an object is only used within a function, it is the function's responsibility to delete the object. In this case it's not even necessary to dynamically allocate the object. Declaring it as a local variable would mean it will get destroyed automatically when it goes out of scope (at the end of the function).
1 2 3 4 5
void test()
{
A objA;
objA.hello();
} // <-- objA is automatically destroyed
#include <iostream>
#include <string>
class A
{
public:
A() { std::cout << "A\n"; }
~A() { std::cout << "~A\n"; }
void hello() { std::cout << "hello\n"; }
};
A* test()
{
A* objA = new A;
objA->hello();
return objA;
}
int main()
{
A* a = test();
delete a;
}
Personally, I would prefer std::unique_ptr instead of raw pointers so that I don't have to call new and delete myself, but I guess that is not what you want to hear...
I'm not sure yet whether it is legitimate, @kakaducsy!
I'm a bit surprised that it seems to work. It is going to be a bit indiscriminate as to which particular object of class A you delete (the last one created at best). Maybe you will need std::map after all.
EDIT: our edits crossed. ptr is a single variable - you can't use it to knock out multiple objects. You will need more than one external pointer.
@kakaducsy, the fact that you can do something doesn't mean that you should.
The following code is horrible. It's an awful way of trying to circumvent passing by argument or return value. I would go back and read @Peter's comments.