Search code examples
c++classvectorcomposite

Using another class as vector in a composite class


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;}
};

Solution

  • 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.