I am trying to create an inheritance hierarchy in C++ using the following simple model: courses, modules, and lessons, in which courses consist of zero or more modules and modules consist of zero or more lessons. Each of these classes also contains other information:
class course
{
private:
const std:string & name_;
const std::duration duration_;
const difficulty difficulty_;
...
};
class module
{
private:
const std:string & name;
const std::duration duration;
...
};
class lesson
{
private:
const std:string & name;
const std::duration duration;
...
};
My questions:
- Would it be correct to have a class that all three of these inherit from, which contains their common properties?
Personally, I think it would be more correct for them to inherit from Vector in the following fashion:
class course : public std::vector<module>
{
private:
const std:string & name_;
const std::duration duration_;
const difficulty difficulty_;
...
};
class module : public std::vector<lesson>
{
private:
const std:string & name;
const std::duration duration;
...
};
class lesson
{
private:
const std:string & name;
const std::duration duration;
...
};
since courses are a collection of modules, and modules are a collection of lessons with some additional properties, and inheriting from vector would provide all of the standard functionality needed to add, remove, etc. modules and lessons.
- Why not both? The way I learned inheritance at school, using Java, I was taught that multiple-inheritance is evil and to stay way from it for proper OO inheritance using the Liskov Substitution Principle, etc. There are a lot of people who don't believe in it and a lot of others who swear by it.
The other possible way would be to have:
class course : public namedentity
{
private:
std::vector<module> modules_;
...
const difficulty difficulty_;
...
};
class module : public namedentity
{
private:
std::vector<lesson> lesons_;
...
};
class lesson : public namedentity
{
private:
...
};
Where namedentity contains all of the common properties, and these private vectors contain their children.
I guess what it boils down to is, are courses really vector<module>
, and modules really vector<lesson>
? Does this violate LSP or other OO principles? Would it be better served by having their children as a property?