Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ - function that returns object

Tags:

// 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()?

like image 520
Kevin Meredith Avatar asked Sep 08 '10 14:09

Kevin Meredith


People also ask

Can a function return an object?

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.

Can we return an object from a function in C++?

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.

What is returning object in C Plus Plus?

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 −

How do you return a class object?

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.


1 Answers

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.

like image 54
Notinlist Avatar answered Oct 27 '22 04:10

Notinlist