Click here to Skip to main content
15,881,139 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C++
#include<iostream>
#include<stdlib.h>
using namespace std;
class Complex{
        private :
                int real,imaginary;
                static int count;
        public :
                Complex(int r,int im){
                        real=r;
                        imaginary=im;
                        Complex::count++;
                }
                Complex(){
                        real=imaginary=0;
                        Complex::count++;
                }
                ~Complex(){
                        cout<<"Destructor called for Complex"<<Complex::count<<endl;
                        Complex::count--;
                }
                void print(){
                        cout<<"Real     :       "<<real<<endl;
                        cout<<"Imaginary:       "<<imaginary<<endl;
                }
                void read(int r,int im){
                        real=r;
                        imaginary=im;
                }
                int getReal(){
                        return real;
                }
                int getImaginary(){
                        return imaginary;
                }
                Complex operator +(Complex &c){
                        Complex c1;
                        c1.read(c.getReal()+real,c.getImaginary()+imaginary);
                        return c1;
                }
};
int Complex::count=0;
int main(){
        cout<<"All is well"<<endl;
        Complex c(100,34);
        Complex c2=c+c;
        c.print();
        c2.print();
        return 0;
}

I am returning an object of complex from + operator what I have purpose fully written in wrong way you might be also thinking that the object must be destroyed after returing because it is created inside of + operator but it isn't destroyed even after the function ends.
Why the c1 which is an object of Complex class is not destroyed? It can be verified with help of the logs that is generated by the destructor.

What I have tried:

The logs generated by destructor indicates that the c1 object of Complex class is not destroyed after the + operator ends.
Posted
Updated 11-Dec-20 22:04pm
v2

1 solution

The resulting object is returned by value - this is a move constructor. Move constructors - cppreference.com[^]
 
Share this answer
 
Comments
CPallini 12-Dec-20 8:50am    
I suppose it is actually copy elision
https://en.cppreference.com/w/cpp/language/copy_elision

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900