In C++ there are pointers, which are implicit in Java: there is a difference between an object (that is an entity in memory) and his address.
In Java, you need to explicitly create an object, because when you write
MyClass name;
you're creating a reference for an object of that class. This means that name identifies a small memory location which contains the real object address.
When you build the whole house using new, it returns only the address, which is assigned to that small memory location.
In C++ there is a better control of memory and you have 2 ways of creating an object:
if you use the statement
MyClass object;
This object is created in the stack. This means that when the function returns, the object is destroyed. Note that the object is automatically created, without using the new operator.
If you want an object to persist the stack destruction, you shall use the new operator, which returns a pointer to the newly created object:
MyClass *objectPtr = new MyClass();
The * placed after the class name, means you're asking for the relative pointer type instead of an allocation of that object.
Remember you have to clean the memory when you don't need the object anymore, or there will be a memory leak:
delete objectPtr;
So, you can do like this:
MyClass *yourfunction(bool param) {
if (param)
return new MyClass(A);
return new MyClass(B);
}
You shall know, anyway, that Pointers aren't safe at all! Giving the user control over pointers can lead to bad code, bad practices and lot of things that aren't good at all Immediate example: what if you forget to clean the memory after object usage?)
In this case, it's better if you use smart pointers, but now there is really too much to say :) Enjoy googling!
HIH