c++ - How to return dynamic object from operator function? -


i quite confused this. how return dynamically allocated object operator function? consider following example:

#include "stdafx.h" #include <iostream> #include "vld.h" using std::cout; class point {     public:     point(int x,int y) : a(x),b(y)     { }     point()     { }     point operator + (point p)     {         point* temp=new point();         temp->a=a+p.a;         temp->b=b+p.b;         point p1(*temp);  // construct p1 temp         delete temp;      // deallocate temp         return p1;     }     void show()     {         cout<<a<<' '<<b<<'\n';     }     private:         int a,b; }; int main() {     point* p1=new point(3,6);     point* p2=new point(3,6);     point* p3=new point();     *p3=*p2+*p1;     p3->show();     vldenable();     delete p1;     delete p2;     delete p3;     vldreportleaks();     system("pause"); } 

can write program without object p1 in case in overloaded operator + function? how can directly return temp?

your highly appreciated.

please me.

you bit confused between java syntax , c++. in c++, there no need new unless want objects dynamically allocated (on heap). use

point temp; // define variable // process return temp; 

in way, local objects created on stack, , won't have care forgetting delete them etc.

returning pointer operator+ wrong

point* operator + (point p)  {      point* tmp = new point;     // process     return tmp; // return pointer dynamically-allocated object } 

it breaks operator+, since won't able chain it, i.e. a+b+c won't work anymore. that's because a + b returns pointer, a + b + c tries invoking operator+ on pointer, not defined. also, there more serious issues, leaking memory during construction of temporary objects in assignments, see @barry's comment below. hope have convinced return object , not pointer it.


Comments

Popular posts from this blog

IF statement in MySQL trigger -

c++ - What does MSC in "// appease MSC" comments mean? -

javascript - Blogger related post gadget image Resize s72-c [ Need Expert Help ] -