3

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();
}
user1887990
  • 101
  • 1
  • 2
  • 8
  • If you change the type of `m_check_sum` to `std::string` (or `std::vector` or some other type with value semantics), then you won't need a destructor, you won't need to follow the [Rule of Three](http://en.wikipedia.org/wiki/Rule_of_three_(C%2B%2B_programming)), and you won't care about the destructor being called too early or too often. – Robᵩ Apr 24 '13 at 17:14

1 Answers1

5

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.

Community
  • 1
  • 1
Armen Tsirunyan
  • 130,161
  • 59
  • 324
  • 434