-1

I have 2 classes, they have a composite relationship. How do I include the class as a vector in another class? Can anyone tell me how to initialize the vector as well?

class Student{
int id;
string name;
public:
 Student(int id = 0, string name = "NA")
: id(id), name(name) {}
int getId() {return id;}
string getName() {return name;}
};

class Faculty{
int id;
string name;
vector<Student> student;
public:
 Faculty(int id = 0, string name = "NA", vector<Student> student)
 {
 id = id;
 name = name;
 student = student;
}
int getId() {return id;}
string getName() {return name;}
};
Coastie
  • 55
  • 7
  • What is `attraction`? – CinCout Jan 06 '16 at 05:57
  • sorry, it's a typo.. – Coastie Jan 06 '16 at 05:58
  • Try giving parameters to member functions (constructors in your case) and members different names. Do you honestly expect a statement of the form `id = id` to set one object to equal to another? Also, to use a vector `#include ` is needed. – Peter Jan 06 '16 at 06:11

1 Answers1

0

If you are going to use the same identifier for both your data members and your constructor parameters, you will need to initialize them with an initialization list-- not in the function body.

class Faculty{
  int id;
  string name;
  vector<Student> student;

   public:
   Faculty(int id = 0, string name = "NA", vector<Student> student={})
   : id(id)
   ,name(name)
   ,student(student)
   {}
};

You can provide a default parameter for the vector with an empty initialization list.

If you are only going to give some of your parameters default values, they must come after your parameters that do not have a defaults specified. This is why your example code would fail to compile.

Trevor Hickey
  • 36,288
  • 32
  • 162
  • 271