mardi 2 juillet 2019

How to enforce derived class members on derived classes

How does one enforce a derived class to have member data of a specific derived type.

i.e.,

class Project {
  public:
    int projdata;
};

class Article: public Project {
};

class Building: public Project {
};

class Emplooyee {
  public:
    std::vector<Project> projs;
}

class Architect: public Employee {
};

class Writer: public Employee {
};

How do I now enforce that Architect objects only have projects of type Building, while Novelist only have projects of type Article? i.e., I want to have something like

class Architect: public Employee {
  public:
    std::vector<Building> projs;
};

and

class Novelist: public Employee {
  public:
    std::vector<Article> projs;
};

I could also store pointers to projects and then store cast them into the correct type. Is there a technique or design pattern to enforce such corresponding inheritance rules on members of derived classes?

Aucun commentaire:

Enregistrer un commentaire