Uniqueness
You say in a comment that what makes makes Garfield
different from Cat
is that it's unique. That's not what a class does for you, though:
Cat* garfield = new Garfield();
Cat* garfieldTheSecond = new Garfield();
// you now have 2 Garfields
The important question is "In which way does the uniqueness matter?".
Concerning "identity", every instance of a class (every time you call new Cat
) is already "unique". Even if you call new Cat("Garfield")
twice, the 2 of them are apart entities; if you change data for one, the other won't be affected.
Concerning only using a name once... well first of all, if you only call new Cat("Garfield")
once (and don't change names afterwards), only one cat with that name will ever exist. That's often enough already.
If you need to enforce name uniqueness, it's similar to real life. You need an "official place" that gives out cat names, and before they give out the name "Garfield", they need to check if they have already given it out. If no name should be used twice, they have to keep a list of names they give out.
In code, the quick and easy solution for this is to add a list of strings as a static variable in the class, and check against that during creation.
The horrible "Animal" example
The "Dog is a subclass of Animal" example is a staple of programming beginner tutorials. I absolutely hate it, because it completely misleads beginners. It pretends subclasses are this awesome everyday thing that can solve a lot of problems.
In reality, in the industry you rarely use it because you run into problems really quickly. At one job, we built up an application over 4 years and we used subclasses like, 3 times in there. You wouldn't make a subclass for Dog
, let alone another one for a Dog
with a certain name.
This is not a direct answer to your question, but before the horrible Animal example messes your understanding up like it did mine, I'd advise you to first read up on the problem by searching for "diamond problem", and then read up on the solution by searching for "composition over inheritance".
Cat* garfield = new Cat("Garfield"); Dog* einstein=new Dog("Einstein");
- there is probably no need to create individual classes for them.