I have a question about constructor. When is constructor called and when is not?
Look at this sample code
Code:#include <iostream.h> class SimpleClass { public: SimpleClass(); ~SimpleClass(); friend ostream & operator<<(ostream &,SimpleClass&); int GetData(); void SetData(int); void testfunction(SimpleClass); private: int itsData; }; SimpleClass::SimpleClass():itsData(0){cout<<"Default constructor called!"<<endl;} SimpleClass::~SimpleClass(){cout<<"Destructor called!"<<endl;} int SimpleClass::GetData(){return itsData;} ostream& operator<<(ostream &o, SimpleClass &rhs) { o<<rhs.GetData(); return o; } void SimpleClass::testfunction(SimpleClass obj) { //why at this place default constructor is not called obj.SetData(2); }//Destructor is called when obj goes out of scope void SimpleClass::SetData(int i) { itsData=i; } int main() { SimpleClass obj; //this will cause message "Default constructor called" cout<<obj<<endl; obj.testfunction(obj); return 0; }
When this is executed I get messages
Default constructor called!
0
Destructor called!
Destructor called!
Default constructor is called when I explicitly create object at line SimpleClass obj;
destructor is called when going out of function and at the end of the program, But why constructor is not called in function to create object obj or it is?
How can destructor be called and constructor cannot or some other constructor is called.
This is a bit confusing for me, so please help.