For a programming assignment, I need to create a program that uses classes, objects, and operator overloading to "marry" two people together. Here's what I have:
#include <cstdlib>
#include <iostream>
#include <vector>
using namespace std;
class Family{
public:
string name;
int age;
//An object pointer of Family to represent a spouse
Family * spouse;
/**
* A constructor that takes 3 arguments
* @param n takes default 'unknown'
* @param a takes default 18
* @param s takes default NULL
*/
Family( string n="Unknown", int a=18, Family * s=NULL){
name=n;
age=a;
spouse=s;
}
friend void operator&(Family a, Family b) { // Marries two family objects
Family A(a.name, a.age, &b);
Family B(b.name, b.age, &a);
a = A;
b = B;
}
friend bool operator&&(Family a, Family b) { // Checks if two Family objects are married
if (a.spouse == &b && b.spouse == &a) {
return 1;
} else {
return 0;
}
}
};
int main(int argc, char** argv) {
//Declaring an object F using a name and age=18 representing a female.
Family F("Nicky",18);
//Declaring an object M using a name, age =19 and spouse being the previous object
Family M("Nick",19,&F);
//1pt Check if they are married or not using the operator &&
cout << "Are they married " << (F&&M) << endl;
//1pt Marry them to each other using the operator &
(F & M);
//1pt Check if they are married or not using &&
cout << "Are they married " << (F&&M) << endl;
// Printing the spouse of the Female
cout<< "The spouse of female "<< F.spouse->name<<endl;
// Printing the spouse of the male
cout<< "The spouse of male "<< M.spouse->name<<endl;
return 0;
}
When I check if they're married to each other using &&, it returns 0 both times. When it tries to print the name of the spouse (F.spouse->name), I get a segfault. I'm very inexperienced with pointers, but I'm reasonably sure the problem is in the & operator. I'm just not sure what's going wrong.