// Assume class definition for Cat is here. Cat makeCat() { Cat lady = new Cat("fluffy"); return lady; } int main (...) { Cat molly = makeCat(); molly->eatFood(); return 0; }
Will there be a "use after free" error on molly->eatFood()
?
A function can also return objects either by value or by reference. When an object is returned by value from a function, a temporary object is created within the function, which holds the return value. This value is further assigned to another object in the calling function.
Passing and Returning Objects in C++ In C++ we can pass class's objects as arguments and also return them from a function the same way we pass and return other variables. No special keyword or header file is required to do so.
An object is an instance of a class. Memory is only allocated when an object is created and not when a class is defined. An object can be returned by a function using the return keyword. A program that demonstrates this is given as follows −
If a method or function returns an object of a class for which there is no public copy constructor, such as ostream class, it must return a reference to an object. Some methods and functions, such as the overloaded assignment operator, can return either an object or a reference to an object.
Corrected your program and created an example implementation of class Cat
:
#include <iostream> #include <string> class Cat { public: Cat(const std::string& name_ = "Kitty") : name(name_) { std::cout << "Cat " << name << " created." << std::endl; } ~Cat(){ std::cout << "Cat " << name << " destroyed." << std::endl; } void eatFood(){ std::cout << "Food eaten by cat named " << name << "." << std::endl; } private: std::string name; }; Cat* makeCat1() { return new Cat("Cat1"); } Cat makeCat2() { return Cat("Cat2"); } int main (){ Cat kit = makeCat2(); kit.eatFood(); Cat *molly = makeCat1(); molly->eatFood(); delete molly; return 0; }
It will produce the output:
Cat Cat2 created. Food eaten by cat named Cat2. Cat Cat1 created. Food eaten by cat named Cat1. Cat Cat1 destroyed. Cat Cat2 destroyed.
I suggest you learn a basic book about the C++ cover to cover before continuing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With