Strange destructor behavior

closed account (jwC5fSEw)
The C++ book I'm following is just getting to classes. I'm completing an exercise where I have to make a class with a single member variable, an int. The constructor sets the member int to the value given and outputs a string and the member int. The destructor does the same. Here's my program:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
using namespace std;

class Simple {
    int num;
    public:
        Simple(int num){
            cout << "Simple() constructor called\n";
            cout << "num is " << num << endl;
        }
        ~Simple(){
            cout << "Simple() destructor called\n";
            cout << "num is " << num << endl;
        }
};

int main(){
    Simple test(12);
    return 0;
}


Yet it outputs:

Simple() constructor called
num is 12
Simple() destructor called
num is 2009288258


I can't figure out why num doesn't display properly in the destructor.
Your constructor doesn't initialize the value of this->num. You are instead printing the value of the local num.

Plug: Use this-> as much as possible when referring to member variables (or don't name parameters with the same name as a member variable).
Last edited on
closed account (jwC5fSEw)
Ohhhh, I kinda thought that the constructor would automatically associate it with the member variable num. I added the line this->num = num; to the constructor and it works as it should now, thanks!

EDIT: Occurred to me after I typed this that it would probably just be easier to change the argument's name.
Last edited on
Use this-> as much as possible when referring to member variables

-1

(or don't name parameters with the same name as a member variable).

+1


;P
Use this-> as much as possible when referring to member variables

I don't really see the point of that....
(or don't name parameters with the same name as a member variable).

But this should really be obvious.
use following code:

Simple(int num):num(num){
cout << "Simple() constructor called\n";
cout << "num is " << this.num << endl;
}
this.num doesn't work.
closed account (jwC5fSEw)
(or don't name parameters with the same name as a member variable).

But this should really be obvious.


Yeahhh, I'm a little ashamed that I couldn't figure that out >_>
Last edited on
@PJYang2010
'this' is a pointer to the object being manipulated, so you can't acces member functions or variables via dot operator unless you do (*this).num though this->num looks way better.
I really like the way the '->' operator looks :D
Last edited on
Topic archived. No new replies allowed.