0

I stumbled upon a C++ book in the library and have been following it ever since, trying to do the exercises in that book. The one thing that confused me was the answer to one of the exercises I had gotten wrong. I'm a noob and my question is "How do the class functions work in setting values for arrays?". If that doesn't make any sense, bear with me. The example I give below is the author's example, not mine.

#include <iostream>
using namespace std;

class Point {
private:            // Data members (private)
int x, y;
 public:              // Member functions
void set(int new_x, int new_y);
int get_x();
int get_y();
};

int main() {
Point array_of_points[7];

// Prompt user for x, y values of each point.

for(int i = 0; i < 7; ++i) {
    int x, y;
    cout << "For point #" << i << "..." << endl;
    cout << "Enter x coord: ";
    cin >> x;
    cout << "Enter y coord: ";
    cin >> y;
    array_of_points[i].set(x, y);         
}

// Print out values of each point.

for(int i = 0; i < 7; ++i) {
    cout << "Value of array_of_points[" << i << "]";
    cout << " is " << array_of_points[i].get_x() << ", ";
    cout << array_of_points[i].get_y() << "." << endl;
}

return 0;
}

void Point::set(int new_x, int new_y) {
if (new_x < 0)
    new_x *= -1;
if (new_y < 0)
    new_y *= -1;
x = new_x;
y = new_y;
}

int Point::get_x() {
return x;
}

int Point::get_y() {
return y;
}

My question is how does the void Point::set function of class Point seem to save the values of the variables x and y in the array. It confuses me because it's like it's storing it but not quite...

Note: This is not for an assignment. Thank you.

EmCode
  • 17
  • 7

1 Answers1

1

Point array_of_points[7]; means that you have created 7 Point objects in stack area in memory. Each array element is an object that contains two attributes x and y. Each time you called the method array_of_points[i].set(x, y); means that the i'th object called set() method to assign new_x and new_y for the object.

illustration

TaQuangTu
  • 2,155
  • 2
  • 16
  • 30
  • Yes, but how does it remember for every two values. From what I think, as soon as the user delivers input, x and y change. So then when I print it out it shouldn't be able to give me all the values? Sorry. Can you explain a bit more? – EmCode Sep 25 '18 at 03:25
  • If you want to know how is an object stored in memory, you can read at here https://stackoverflow.com/questions/12378271/what-does-an-object-look-like-in-memory. – TaQuangTu Sep 25 '18 at 03:38