mixin terminology - c++

In classic inheritance, Derived inherits from Base. With mixins, the (technical) base class is usually called the Mixin. What is the proper term for the (technical) class that inherits from the Mixin?
I want to know this so I can name my template parameters accordingly.

The use of a mixin class is an implementation detail that doesn't impact the result as directly as a base/derived relationship in a typical inheritance tree, so I'm not sure it deserves its own name. The one time I used it most successfully there was already an existing base class that was required (MFC's CDialog), so multiple inheritance was used and my mixin wasn't the first one on the list.
If you really have to pick a name, Derived is probably as good as any.

Probably there is no accepted name for that.
Try:
Final
Concrete
Complete

Related

Is it better to cast a base class to derived class or create a virtual function on the base class?

According to this answer, dynamic_cast'ing a base class to derived class is fine, but he says this shows that there is a fundamental problem with the code logic.
I've looked at other answers and using dynamic_cast is fine since you can check the pointer validity later.
Now in my real problem the derived class has a GetStrBasedOnCP function which is not virtual (only the derived class has it) and I have to access it.
What is better, to create a virtual void GetStrBasedOnCP on the base class and make it virtual on the derived OR, to just cast the base class pointer to derived class?
Oh also notice that this is a unsigned int GetStrBasedOnCP so the base class must also return a value...
There are more than two answers to the "what is better" question, and it all depends on what you are modeling:
If the GetStrBasedOnCP function is logically applicable to the base class, using virtual dispatch is the best approach.
If having the GetStrBasedOnCP function in the base class does not make logical sense, you need to use an approach based on the actual type; you could use dynamic_cast, or
You could implement multiple dispatch, e.g. through a visitor or through a map of dynamic types.
The test for logical applicability is the most important one. If GetStrBasedOnCP function is specific to your subclass, adding it to the base class will create maintenance headaches for developers using and maintaining your code.
Multiple dispatch, on the other hand, gives you a flexible approach that lets you access statically typed objects. For example, implementing visitor pattern in your base class lets you make visitors that process the subclass with GetStrBasedOnCP function differently from other subclasses.
Does it make sense for the base class you have to have the virtual function in it?
If it does not then you should not include the function in the base class. Remember that best practices cover the general case. There are times you need to do things you wouldn't normally do to get the code working. The key thing is you need is clear, concise, understandable code
There's a lot of "it depends".
If you can guarantee that the base pointer is the correct child pointer, then you can use dynamic_cast.
If you can't guarantee which child type the base pointer is pointing to, you may want to place the function in the base class.
However, be aware that all children of the base class will get the functionality of whatever you place into the base class. Does it make sense for all the children to have the functionality?
You may want to review your design.

What benefit I will get to create an abstract class rather than the base class in CPP?

In our project - C++, we have the generic module called "ContentCache". From this contentcache, we have derived the customer specific contentcache - for example - Airtel, TataSky. For example, the base contentCache has the method - create the database table, store the basic information. The other types of contentcache which has a relationship like airtel content cache is a type of contentcache. This airtel content cache is customized - overriden a few methods. However, the rest of it are the same. On a few products, we simply use the generic - contentCache. My question is do we need an abstract class - ContentCache - IcontentCache. Also, what is the good way - creating an abstract class or just create a generic base class. What advantage do we get with the IContentCache- i.e. abstract class. I am looking an answer from the design pattern point of view. Also, the programming point of view.
usually you use an abstract class if you define some functionality which can only be used if some additional, unavailable information (or functionality), is needed for that class to work. The unavailable but required information is defined as abstract methods of the class, then derived classes provide that extra information (or functionality).
In your example, if you can usefully have a generic ContentCache then it doesn't need to be abstract. But you might have a design where a ContentCache cannot be instantiated without knowing the name of the specific customer. In this case you might define all of the cache functionality in the abstract base class and have an abstract method which provides the name of the customer. Then in the derived classes you provide the implementation which returns that customer name and the class then has everything it needs to create the cache.
Admittedly this is not a great example as you could just provide the customer name in the constructor of the class, but you mention that in the derived classes you 'override a few methods'. These methods might be candidates for being abstract if they provide functionality which cannot be determined without knowing the customer.
Abstract class is better than just a normal base class. From the design perspective when ever we design a base class , we know that there is going to be inheritance (virtual functions). So we try to collect the common functions in the base class which will mostly be over ride in the derived class. Abstract means hiding the actual implementations from the outside world.Our implementations are our wealth.So base class needs to only work as an interface kind of thing and it should not have any implementation.
Abstract classes are good for you when ever your derived classes are going to ALWAYS use their derived class function definition rathar than using the base class definition.
Normal base classes will be useful , if you are going to use the base class virtual function definition along with the derived class function definition. Normal base class it will be good for small inheritance levels.

Class design to avoid need for list of base classes

I'm currently in the design phase of a class library and stumbled up on a question similar to "Managing diverse classes with a central manager without RTTI" or "pattern to avoid dynamic_cast".
Imagine there is a class hierarchy with a base class Base and two classes DerivedA and DerivedB that are subclasses of Base. Somewhere in my library there will be a class that needs to hold lists of objects of both types DerivedA and DerivedB. Further suppose that this class will need to perform actions on both types depending on the type. Obviously I will use virtual functions here to implement this behavior. But what if I will need the managing class to give me all objects of type DerivedA?
Is this an indicator of a bad class design because I have the need to perform actions only on a subset of the class hierarchy?
Or does it just mean that my managing class should not use a list of Base but two lists - one for DerivedA and one for DerivedB? So in case I need to perform an action on both types I would have to iterate over two lists. In my case the probability that there will be a need to add new subclasses to the hierarchy is quite low and the current number is around 3 or 4 subclasses.
But what if I will need the managing class to give me all objects of
type DerivedA?
Is this an indicator of a bad class design because I have the need to
perform actions only on a subset of the class hierarchy?
More likely yes than no. If you often need to do this, then it makes sense to question whether the hierarchy makes sense. In that case, you should separate this into two unrelated lists.
Another possible approach is to also handle it through virtual methods, where e.g. DeriveB will have a no-op implementation for methods which don't affect that. It is hard to tell without knowing more information.
It certainly is a sign of bad design if you store (pointers to) objects together that have to be handled differently.
You could however just implement this differing behaviour as an empty function in the base class or use the visitor pattern.
You can do it in several ways.
Try to dynamic_cast to specific class (this is a bruteforce solution, but I'd use it only for interfaces, using it for classes is a kind of code smell. It'll work though.)
Do something like:
class BaseRequest {};
class DerivedASupportedRequest : public BaseRequest {};
Then modify your classes to support the method:
// (...)
void ProcessRequest(const BaseRequest & request);
Create a virtual method bool TryDoSth() in a base class; DerivedB will always return false, while DerivedA will implement the required functionality.
Alternative to above: Create method Supports(Action action), where Action is an enum defining possible actions or groups of actions; in such case calling DoSth() on class, which does not support given feature should result in thrown exception.
Base class may have a method ActionXController * GetControllerForX(); DerivedA will return the actual controller, DerivedB will return nullptr.
Similarly, base class can provide method: BaseController * GetController(Action a)
You asked, if it is a bad design. I believe, that it depends on how much functionality is common and how much is different. If you have 100 common methods and only one different, it would be weird to hold these data in separate lists. However, if count of different methods is noticeable, consider changing design of your application. This may be a general rule, but there are also exceptions. It's hard to tell without knowing the context.

What is special about the abstract class mechanism in C++?

I have question that bothers me for few days.
Abstract class is a special type of class that we cannot instantiate, right?. (Which is denoted/specified by giving a "= 0" to at least one method declaration, which looks like an afterthought).
What are the extra benefits that the abstract class mechanism brings to C++, that a 'normal' base class cannot achieve?
According to the wikibooks section on abstract classes:
It's a way of forcing a contract between the class designer and the users of that class. If we wish to create a concrete class (a class that can be instantiated) from an abstract class we must declare and define a matching member function for each abstract member function of the base class.
As mentioned, it's a way of defining an interface to which derived classes must adhere. Their example of the Vehicle abstract class is very apropos: you'd never have just a Vehicle in real life, you'd have a Ford Explorer or a Toyota Prius, but those both conform to (for the sake of argument) a base set of functionality that being a Vehicle might define. But, you can't just go to the Vehicle dealership and drive a Vehicle off the lot. Thus, you'd never want to be able to construct and use a base Vehicle object where you'd really want a specialized, derived object.
This offers the best way in C++ to define an interface without any default implementation.
C++ does not have C#'s interface concept.
It's the equivalent of what Java turned into "interfaces". Basically, it implies that the class itself is not usable - you need to override all pure methods.
An example is MFC's CView class which has a pure OnDraw method - the basic CView doesn't do anything and is as such useless. You have to override OnDraw.
(Btw - it is still possible to provide an implementation for a pure method, and subclassed implementations can fall back to it, but they still have to provide their own override.)
They are used as a base class in a class hierarchy design.
Abstract classes are used to define a clean interface for all derived classes.
At design stage, abstract classes define an interface, per specification and derived classes implement the desired functionality accordingly.
Also using abstract classes instead of "normal" classes helps separating the implementation details from the interface.
A concrete class implements an interface, but the abstract class defines it. You could use a concrete class as a base class in your design but abstract classes are not meant to be used directly in code and can not be instantiated. They serve as prototype.
By using the "normal" class as you say, you have to define an implementation for all methods.
Don't think of it at the class level.
Look at the method, and think of what it should do in the default case:
virtual std::string getName() const = 0;
What would be a right implementation for this method ? There is none than I can think of.
By marking it "pure virtual", you ensure that if the user ever get an instance of a class derived from your interface, then this method will have a sensible behavior.
The only other way to do this would be a throw NotImplemented("getName"); body, but then you'd discover the issue at runtime, not at compile-time, which is not as nice :)

Proper inheritance

What is meant by proper inheritance?
This thread gives a nice summary:
Proper inheritance occurs when the derived class "IS A" specialized type of the base class. Example Cat IS A Animal.
Improper inheritance occurs when a class is inherited from merely for code reuse without having any other relationship. Example Cat Inherits from Engine. A Cat is not an engine however both an engine and a cat purr.
I would like to add to what Justin and Baxter said.
The term proper inheritance is not really well-defined. Properly using inheritance is quite a subjective issue...
Consider the following example:
An interface: Bird
A concrete class: Ostrich
Should Ostrich inherits from Bird ? From a zoological point of view it makes sense, but from a Computer Science point of view... not so much. If Bird has a fly method, then how am I supposed to handle this in Ostrich::fly :x ?
There is somewhat of a war in the CS community. Indeed you'll regularly see books where Circle inherits from Ellipse (or the other way around) when it doesn't really makes sense from a CS point of view.
So my own little definition:
Considering that the interface defines precise semantics for each of its methods, a concrete class should only inherit from the interface if the implementation of each of the method matches the semantics specified.
Perhaps first we should recall what the value of inheritance itself is. Inheritance is a mechanism for both code reuse and interface reuse (polymorphism). But you can have code reuse without inheritance by using composition and delegation. And in many languages you can have polymorphism without inheritance, but not all languages. In a strongly typed language such as C++, polymorphism, which is itself another important code reuse mechanism, can only be achieved using inheritance. In fact, C++ distinguishes between public and private inheritance for interface and code reuse respectively. More on this later.
Generally one thinks of a class's methods as creating a contract with clients of the class: It guarantees that as long as you call a method having met certain preconditions, the method will deliver certain results. "Proper" inheritance is such that the subclass instance can be substituted for its parent class without violating the parent's contract. That is, none of the subclass's methods should override its base class's methods requiring stricter preconditions nor delivering more "less" results. Returning to C++, since there is a clear distinction between public and private inheritance where the former is required so that you may substitute a subclass instance for a base class instance, it is generally considered "proper" that the substitution be semantically correct. Otherwise why not use private inheritance?
Is Ostrich a valid subclass of Bird? It depends on what your abstraction of Bird is? If the Bird class has a method Bird::fly that does something tangible but Ostrich::fly overrides this to throw an exception and thus delivers "less" than its base class, I would say no. But if class Bird did not have a fly method (there is another subclass Flying_Bird that does), no problem.
My answer is that what holds for C++ is not a bad guideline for any object-oriented language. In a languages like Python where an inheritance hierarchy is not required for polymorphism, people might have a greater tendency to use inheritance just for code reuse. If this reuse is well-documented, it might not be an issue. But when I see a class hierarchy, my expectation is that a subclass is potentially going to be used polymorphically and thus an instance of the subclass can be substituted for an instance of the base class thereby obeyeing the Liskov substitution principle where a subclass is also a subtype.
When inheritance complies with a IS A relationship, as opposed to inheriting purely for code reuse without there being a logical subsumption of the child by the superclass.