Does a constructor / destructor have to have code, or is the function enough?

前端 未结 3 1249
再見小時候
再見小時候 2021-01-24 17:44

So if I have a class

class Transaction {

int no;
char dollar;

public:

    Transaction();
    ~Transaction();
}

And in my constructor / destr

3条回答
  •  再見小時候
    2021-01-24 18:07

    Your class has only simple data members, so you don't even need (or should want) a destructor.

    You should, however, initialize your data members in the constructor:

    Transaction::Transaction()
      : no(0), dollar('$') {
        cout << "Entering constructor" << endl;
    }
    

    Otherwise, they will not be initialized, and may contain random values (C++ doesn't guarantee initialization of primitive non-static members to any particular value if you don't initialize them in the constructor). This can be particularly insidious if you have pointer members.

提交回复
热议问题