I’m moving from Java to C++ right now and I’m having some difficulties whenever a commonly used concept in Java doesn’t map directly into C++. For instance, in Java I would do something like:
Fruit GetFruit(String fruitName) {
Fruit fruit;
if(fruitName == "apple") fruit = new Fruit("apple");
else if(fruitName == "banana") fruit = new Fruit("banana");
else fruit = new Fruit("kumquat"); //'cause who really wants to eat a kumquat?
return fruit;
}
Of course, in C++ the Fruit fruit; statement actually creates a fruit. Does this mean I have to have a default constructor? This seems unsafe! What if my default fruit escaped?
C++ gives you much more headache when it comes to creating fruits. Depending on your needs, you can choose one of the following options:
1) create a Fruit on a stack and return a copy (you need a copy constructor) then and must provide some default fruit in case the name does not match:
2) create a Fruit on a heap and take care, that there could be null-pointer returned and also remember to delete this fruit somewhere and take care that it is deleted only once and only by its owner (and take care that noone holds a pointer to the deleted fruit):
3) and finally, use a smart pointer to avoid many possible pointer problems (but take care of null pointers). This option is the closest to your Java programming experience: