mercredi 14 septembre 2016

Various Ways to return an object in C++ and Issues with each

Below is the code which has various return statements and all are working perfectly fine. Compiler throws the warning for fun_ret_obj1

Test.cpp: In function ‘myClass& fun_ret_obj1()’: Test.cpp:45: warning: reference to local variable ‘myObj’ returned

But still the output seems to be fine.Is it by Chance? Are there any catches with any of the return statements below?
Explanation would be really helpful, Thanks

#include <iostream>
 using namespace std;


 class myClass {
 public:
 int a ;
 myClass()
 {
   a = 10;
 }
 };
 myClass& fun_ret_add()
 {
    myClass *ptr = new myClass();
    return *ptr;
 }

 myClass* fun_ret_ptr()
 {
     myClass *ptr = new myClass();
     return ptr ;
 }

 myClass fun_ret_obj()
 {
     myClass myObj;
     return myObj;
 }

 myClass& fun_ret_obj1()
 {
     myClass myObj;
     return myObj;
 }


 int main()
 {
     myClass obj,obj1;
     std::cout <<"In Main \n";

     myClass *a = fun_ret_ptr();
     std::cout<<a->a<<"\n";

     myClass &b = fun_ret_add();
     std::cout<<b.a<<"\n";

     myClass c = fun_ret_obj();
     std::cout<<c.a<<"\n";

     myClass d = fun_ret_obj1();
     std::cout<<d.a<<"\n";

 }

Aucun commentaire:

Enregistrer un commentaire