Constructors: call function before setting values

Hello!
Please, I called function rect.area() before I set values and , INSTESD (y/n?) of UNDEFINED result , I got 0 (zero) in ideone

http://ideone.com/HDfStd (please, how to mark a link?)

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

class Rectangle {
    int width, height;
  public:
    void set_values (int,int);
    int area () {return width*height;}
};

void Rectangle::set_values (int x, int y) {
  width = x;
  height = y;
}

int main () {
  Rectangle rect, rectb;
  rect.set_values (3,4);
  rectb.set_values (5,6);
  cout << "rect area: " << rect.area() << endl;
  cout << "rectb area: " << rectb.area() << endl;
  return 0;
}


So, my question is: what is difference between 0 and UNDEFINED?

Many thans!!!
If your class does not have a constructor function, the compiler creates a default constructor for you. The constructor it created must have set width and height to 0.
Last edited on
Hello, many thanks!!!
Do ALL compilers do that, or does it vary from compiler to compiler?
does it vary from compiler to compiler?

Yes. When the standard does not require to write particular value to memory area, the compiler is free to do nothing. For example, the MSVC adds instructions to write 0, if you compile a "Debug build", but does not in "Release build".

When the program does not write a value, the value that you will see depends on what was written to that same memory address before your current object did occupy it.


Every (C++11) compiler can/will* provide default implementation for these:
Default constructor
Copy constructor
Copy assignment
Move constructor
Move assignment
Destructor

* The standard has rules.
> what is difference between 0 and UNDEFINED?
0 is just as bad a result as any other number.
Many thanks!!!
Topic archived. No new replies allowed.