Destructor gets called before the end of scope

c++, destructor

Solution

This expression

check("poalim",809877,12,"4578")

creates a temporary object that gets destroyed right after the full expression (;)

Before being destroyed, it is copied to `ob1`, which is destroyed at the end of the main function.

Perhaps you meant to write

int main(){ //note the correct return type of main
  check ob1("poalim",809877,12,"4578"); //direct constructor call
  cout<<ob1.m_check_sum<<endl;
  getchar(); 
}

I really suggest that you should read a good book on C++ fundamentals.

Problem

for some reason, after creating an object in main func., the destructor gets called right away, isn't it supposed to get called only when main finishes? thanks code: ``` #include <iostream> #include <cstring> #include <vector> using namespace std; class check{ //create class check public: string m_bank_name; int m_check_number; int m_branch_number; char* m_check_sum; check ( string bank_name, int check_number, int branch_number, char* check_sum){ int a_size = (strlen(check_sum)+1); m_check_sum = new char[a_size](); for (int i=0;i<a_size;i++) { m_check_sum[i]=check_sum[i]; } m_bank_name= bank_name; m_check_number = check_number; m_branch_number = branch_number; } ~check (){ delete [] m_check_sum; cout<<"deleted!"<<endl; } }; void main(){ check ob1= check("poalim",809877,12,"4578"); cout<<ob1.m_check_sum<<endl; getchar(); } ```

Original source

Related problems