# Print and compare structure comprising two integers

The question is from: https://www.learncpp.com/cpp-tutorial/member-functions/

Create a struct called IntPair that holds two integers. Add a member function named print that prints the value of the two integers

Here's the code I have written, with main() already provided for exercising the struct:

#include <iostream>
#include <cstdlib>

/* Question:
* Create a struct called IntPair that holds two integers. Add a member function
* named print that prints the value of the two integers.
*/

struct IntPair {
int a {};
int b {};

void print() {
std::cout << a << " " << b << "\n";
}
};

int main()
{
IntPair p1 {1, 2};
IntPair p2 {3, 4};

std::cout << "p1: ";
p1.print();

std::cout << "p2: ";
p2.print();
}


And here's the output:

p1: 1 2
p2: 3 4


It was followed up with another question:

Add a new member function to IntPair named isEqual that returns a Boolean indicating whether one IntPair is equal to another.

Here's the code I wrote for it, with the main() already provided:

#include <iostream>
#include <cstdlib>

/* Question:
* Add a new member function to IntPair named isEqual that returns a Boolean
* indicating whether one IntPair is equal to another.
*/

struct IntPair {
int a {};
int b {};

void print() {
std::cout << a << " " << b << "\n";
}

bool isEqual(const IntPair& ip) {
return a == ip.a && b  == ip.b;
}
};

int main()
{
IntPair p1 {1, 2};
IntPair p2 {3, 4};

std::cout << "p1: ";
p1.print();

std::cout << "p2: ";
p2.print();

std::cout << "p1 and p1 " << (p1.isEqual(p1) ? "are equal\n" : "are not equal\n");
std::cout << "p1 and p2 " << (p1.isEqual(p2) ? "are equal\n" : "are not equal\n");
}


And here's the output:

p1: 1 2
p2: 3 4
p1 and p1 are equal
p1 and p2 are not equal


## Review Request:

Anything. Everything.

• This felt like a C struct on steroids. Mar 31 at 23:18
• That's a terrible assignment. In C++, print() is usually spelt << and isEqual() is spelt ==. This looks very much like a translation of a Java exercise, rather than something to develop C++ knowledge. Apr 1 at 8:43
• I feel like a and b could be renamed to x and y? Apr 1 at 9:01

Neither function should be modifying the contents of the object, so they should both be declared const:

//               🔻🔻🔻
void print() const {
//               🔺🔺🔺

//                                  🔻🔻🔻
bool isEqual(const IntPair& ip) const {
//                                  🔺🔺🔺


To demonstrate the need for this, we need only make a small adjustment in main():

    const IntPair p1 {1, 2};
const IntPair p2 {3, 4};

• Does this matter even when the object is say something like a Lexer and shouldn't be made const? Apr 2 at 14:37
• In C++, we pass around const references all the time. It's the way for the function to promise it won't make changes to the object (and usually more efficient than passing a copy, even for objects that are copyable). Apr 4 at 7:08