#include<iostream>
using namespace std;

class sample
{
     static int i;
    public:
        sample()
        {
            cout<<"base:construcotr"<<endl;    
            cout<<this<<endl;
        }    
        ~sample()
        {
            cout<<"destructor"<<endl;
            cout<<this<<endl;    
        }
        sample(const sample &s)
        {
            cout<<"copyconstructor"<<endl;    
            cout<<this<<endl;
        }
     /* sample operator =(sample s)
        {
            cout<<"==operator called"<<endl; 
            cout<<&s<<endl;  
            return s;
        }*/
        
};
int sample::i=0;
sample fun(sample x)
{
    cout<<"hello"<<endl;
    cout<<&x<<endl;
    return x;    
}


void hello()
{
    sample s;
    //cout<<"now calling the func"<<endl;
    sample s2;
    s2=fun(s); 
    cout<<"s2 created by simple"<<endl;
 //  s2=fun(s);             //s2.operator=(fun(s));
       cout<<"after return from func"<<endl;
       
       
}   

int main()
{
    hello();
    int t;
    cin>>t;
    
}

in the above program 4 constructors are called (including copy constructors) and 4 destructors as expected(as expected).
but when i uncomment the assingment operator 5 constructors are called and 5 destructors are called but i expected 6 constructors to be called ...
since fun() and operator = () have same prototypes i expected them to behave in sa similar manner but this is not happening....
when fun() is called a constructor is calles for passing the args by value and then another constructor called for returning from the fun() but when assigment operator is called only one object is created that also for returning the value but not for passing the arguments
why????

sample s; //default ctor or if is provided then it is called
sample s1(s); //copy ctor is called
sample s2 = s1 ; //could use both copy ctor and assignment or just one.
sample s3;
s3 = s2; //use the assignment operator

sample s4( 5, "string") ; //use the provided ctor with same arguments.
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.