If a class does two broad things simultaneously then inheritance can work great. For example, a User class that inherits from a DB mapper class. I don't want to have to tell my class how to write a record to the DB. All that code can be centralized into one thing and then relied upon for its uniformity across all my models.
This isn't true the way most people use inheritance though. They do things like Sword inherits from Weapon and Weapon inherits from Item. But this just asks for trouble because as requirements get more complex there are more edge cases and the complexity bubbles up into overriding the inherited methods, which makes them less reliable from different calling contexts, or flipping the OO script and pushing class-based-if-statements in the ancestor class.
Then you step back and say "why did we make Sword a weapon in the first place?" and the answer was we had logic somewhere else in the code that did things like check if a user was armed. Well we don't need inheritance for that at all. We can use plain old methods and properties / duck typing.
It doesn't really matter because both of these things can be better solved using composition + traits/interfaces anyways.
The funny thing is that languages like C# and Java abandoned mixins but kept deep inheritance hierarchies. When I did C++ more we used multiple inheritance a lot but with only one or two layers deep. This worked extremely well and now that that I am doing more in C# I miss it a lot.
And in defense of inheritance, the Liskov Substitution Principle is extremely useful and makes a lot of sense.
If a function accepts a `Weapon` as parameter, surely you should be able to pass it a `Sword`.
That always seems to the problem with deep hierarchies after a while. Suddenly you have something where one of the inherited methods shouldn't be there. You can't take it away so you have to do something clunky like throwing an exception or making it empty.
In contrast, non class based languages such as Haskell struggle to model problems that are trivial in OOP, such as how to reuse 90% of existing functionality but override 10% with more specialized behavior. Good luck solving that problem elegantly with type classes.
"Sword" instances may have specific properties that make them incompatible with a "weapon" superclass. Is a broken sword still a weapon? How about a sword with no handle? Or a sword that has been magically transformed into a flower? Is that still a sword and a weapon, or is it now "really" a flower, and should inherit all flower methods while throwing away all weapon methods?
You can duck type and/or RTTI your way out of this problem, but you can't avoid the fact that traditional OOP is very bad at handling these "it depends" cases, because the only relationship it supports is a strict and static inheritance hierarchy.
Unfortunately many domains, including natural language, can only be described by mutable context-dependent relationships.
In the real world, swords don't turn into flowers, so you might think you're safe. (Except that you might want to include object mutability in a game...)
But in NL the meaning of a phrase can change according to social setting, unstated subtext, speaker gender, age, and even time of day. It's all context, and it can't be ignored without losing essential detail.
All current typing systems seem to be attempts to enforce limited-scope static relationships between opaque atomic objects with more or less static properties.
Mutable context-dependent relationships are everyone's worst nightmare in CS. Academic CS seems to have spent most of its career trying to pretend they don't exist, or if they do, to make them go away.
This is sold on the basis of making more reliable code. In fact it simply doesn't work elegantly for entire classes of problems, including many problems for which it seems to work just fine if you describe them in words, until you have to think about all the possible details.
The worst case output is intolerant brittle code with limited features, and the best is an encrustation of exceptions, edge cases, and work-arounds.
Note I'm not saying there's a simple answer, because there isn't. This is a research-grade problem, and it's barely been considered.
I am saying - beware of simple principles like LSP that claim to solve this problem. Because there are many situations in which they simply don't.
You don’t need inheritance to achieve this.
Your User class contains data and probably some business logic. The fact that it’s going to be persisted in a database at some point is a detail that the class shouldn’t know.
Consider using the data mapper pattern (or an ORM implementing this pattern). In this pattern, your User object doesn’t even know it will be persisted. It doesn’t have any parent class. You just manipulate your entities like a graph of plain objects, and when you have finished you ask the data mapper to persist them. In my experience this is much better than what you are describing, which look like the Active Record pattern.
> If a class does two broad things
Doing this is a violation of one very commonly accepted principle: The single responsibility principle.
Myself, I wouldn't even put any business logic in the User object, except maybe representational logic (e.g. have a couple of helper methods that return multiple representation of the same piece of data).
One of the best things to do is separate behavior from data in the first place, which feels kind anti-OO philosophy, but is definitely easier to reason about and work with.
Inheritance is very useful especially in game programming (in context of OP), and hardly ever anywhere else. In games it's useful to be able to pass around references to an object or have systems that manage pools of objects at exactly the hierarchy of inheritance that makes the most sense for the manager of that system. Not many other applications need to pass around objects between various hierarchical management systems as much.
I think inheritance shouldn't be taught in intro-level programming classes. It's presented as "how to do all things in OOP, shove all the things into multi-level child classes" when really it should be "here's an advanced concept for situational architecture optimization". It defeats the purpose when you do multiple levels of inheritance and no longer ever use the parent classes for anything.
This is because OOP is good at modelling objects and games are modelling objects.
But let's be serious for a minute here: even regular inheritance has hardly ever led to the kind of nuclear disaster than most pundits claim.
It makes your code base a bit more unwieldy and a bit harder to evolve, but it's really not the end of the world.
This sentence does not make sense. If you want to have a class composed of two other classes, whose behaviour is defined at run-time - say, a generic "Engine" object which is composed of a "GraphicsRenderer" and an "AudioRenderer" where the first one can be a D3D renderer or an OpenGL renderer and the second can be an XAudio or OpenAL renderer, you have to have inheritance somewhere, because you have to store at least one function pointer at some point. std::function in C++ is implemented with inheritance. Rust traits are based on inheritance. However you look at it, you can never completely "get rid" of inheritance if you want to hide both code and data behind a single pointer. Hell, even the linux kernel written entirely in C reimplements vtables by hand for device drivers because it makes so much sense.
The consensus is to use inheritance of interfaces and use composition to implement the interfaces.
Hence my phrasing: "Inheritance is better achieved through composition".
- you have to at least implement the destructor if you are going to use the abstract class across multiple DLLs - else, dynamic_cast won't work since each DLL may have its own type_info object for the abstract class
- even if a method is marked abstract, it can still have a default implementation: https://gcc.godbolt.org/z/bAE7v6 though other prominent OO languages are slowly catching up with this ;)
Also, C++ has abstract classes with only pure virtual functions, which accomplish the same thing.
A consensus by the "maximization of boilerplate" rule.
Inheritance is the most powerful tool available at the OOP land. It's the one thing that FP languages still didn't replace with enough added advantages to make the OOP stuff look like a toy. So if you are programming in OOP while avoiding inheritance, you would be certainly better in another paradigm.
(And, of course, powerful tools are easy to misuse. That's no reason for forbidding them.)
Assuming this is the case: why do you disagree and what do you think is the cause of this difference in opinion?
Look how I abused inheritance in this assembler (for a Lisp virtual machine):
http://www.kylheku.com/cgit/txr/tree/share/txr/stdlib/asm.tl
The object system is used to define opcodes. Methods on these objects (which get instantiated as singletons) then handle assembling and disassembling.
There is a macro defopcode-derived which defines an opcode similar to another one, using inheritance.
There is no reason for the relationship to go one way or the other; it's just "this thing is like that thing, except for this slight difference". The inheritance could basically go in either direction.
Note that defopcode-derived doesn't even have provision in its syntax to specify behavior; the code is 100% re-used. The only thing different about the derived opcode is the instruction mnemonic and the opcode bits. Inheritance is used just to override a number and symbol which are static slots.
To wit, implementation inheritance gives you a sum type (e.g. a Shape is either a Circle, or a Square, or…) whereas interface inheritance gives you a product type (class Foo : IBar, IBaz means that Foo is an IBar and an IBaz).
Classes are very well suited to statically formalize the communication points (aka "interfaces", "protocols") between the various parts of your program.
The fact that a concrete class might have a state is actually irrelevant (indeed, we generally make all of our data members "private").