Garmaine Staff asked 2 years ago

As part of a C++ assignment to learn more about pointers and objects, I have a class that represents family members. One of the parameters is a vector pointer, "kids", which should contain objects of that same class. I've been told to use operator overloading with '<' to add newly-created objects to the 'kids' field of another object. Here's what I currently 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 vector pointer of Family to represent children 
   vector<Family>* kids;

   /** 
   * A constructor that takes 4 arguments 
   * @param n  takes default 'unknown' 
   * @param a  takes default 18
   * @param s  takes default NULL
   * @param v  takes default NULL
   */ 
   Family( string n="Unknown", int a=18, Family * s=NULL,vector<Family> * v=NULL){
       name=n; 
       age=a; 
       kids=new vector<Family>; 
       spouse=s; 
   }
   /**2pts
    * Create a method that overloads < 
    * The method will add a Family object to the list of children
    * @param a Family object 
    */
   int kCount = 0;
   void operator<(Family f) {
       (*kids)[kCount] = f;
   }
};
int main(int argc, char** argv) {
    //Declaring an object F using a name and age=35 representing a female.
      Family F("Nicky",35);
    //Declaring an object M using a name, age =39 and spouse being the previous object
      Family  M("Nick",39,&F);

    Family c0("Ricky", 15);
    Family c1("Bicky", 12);
    Family c2("Dicky", 9);
    Family c3("Micky", 6);
    //2pts Add the kids to M using the operator <
    M < c0; 
    return 0;
}

When I attempt to run this, I get a segfault. I'm still very inexperienced with pointers, so I really don't know how to resolve this.