Public feed
#894504
#include <iostream>
using namespace std;
// Class declaration -- declared outside the main() function
class Point {
private:
int x, y;
public:
Point() {} // default constructor
Point(int new_x); // alternate constructor
Point(int new_x, int new_y); // ordinary constructor
// other member functions
void set(int new_x);
void set(int new_x, int new_y); // These are the function prototypes, but
int get_x(); // we still need function definitions
int get_y();
};
int main() {
Point pt1, pt2; // Create two new objects, both of type Point, using the default constructor
Point pt3(5, 10); // Create another object, using the regular constructor
Point pt4(1000); // Try out the new constructor!
cout << "The value of pt1 is " << pt1.get_x() << ", " << pt1.get_y() << endl;
cout << "The value of pt3 is " << pt3.get_x() << ", " << pt3.get_y() << endl;
cout << "The value of pt4 is " << pt4.get_x() << ", " << pt4.get_y() << endl;
cin.get();
return 0;
}
// Set & get function definitions
// The set function simply accepts a value from the calling function, and
// sets that value for x & y. If the args are negative, it will reverse the sign.
//
Point::Point(int new_x) {
set(new_x);
}
Point::Point(int new_x, int new_y) {
set(new_x, new_y);
}
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;
}
// Must have a function definition for the alternate constructor as well as the
// regular constructor.
//
void Point::set(int new_x) {
if (new_x < 0)
new_x *= -1;
x = new_x;
y = 0;
}
// The get functions will simply return the x & y values that have been set above
//
int Point::get_x() {
return x;
}
int Point::get_y() {
return y;
}