Should downcasting be avoided while using a class hierarchy in C++? - c++

Let's say I'm writing an application which works with projects, and exposes different functionality depending on the type of the project. I have a hierarchy of classes for the different types of projects:
class AbstractProject
{
};
class ProjectA : public AbstractProject
{
};
class ProjectB : public AbstractProject
{
};
class ProjectC : public AbstractProject
{
};
Now, I was planning to have an AbstractProject *_currentProject pointer as a member in the application's main class, pop up a dialog box on startup and based on the selection, do:
_currentProject = new ProjectB(); // e.g.
Later, I'll have to downcast the pointer to the specific type to utilize the functionality specific to different Project-s. Somehow this makes me feel uneasy. Is there a Better Way of doing this?

Better way is to define pure virtual methods in base class and later implement all specific functionality in overloads in derived classes. Then call that method.

Yes you should use virtual methods instead, whenever possible.

The Command and the Visitor pattern may both apply here. You should decide for yourself which fits better for your case.
http://en.wikipedia.org/wiki/Command_pattern
http://en.wikipedia.org/wiki/Visitor_pattern

In pure OO, you should have virtual methods like everyone suggested. However, if you still need to go for specific member functions, try using one of the design pattern, may be command or visitor or even decorator...

Related

can an abstract class inherit from a "normal" class?

I am looking for a useful example of multiple inheritance in C++ and found an example for Window-creation here: A use for multiple inheritance? and modified it a bit. It conceptually looks like this:
class Window
class Skinable // abstract
class Draggable // abstract
class DraggableSkinnableWindow : Window, Draggable, Skinnable
I think this is supposed to be a good example where MI makes sense. Since it doesn't make sense to implement a class of Skinable, it should be defined abstract.
Now: How would this look like if I would not use the concept of MI.
I would have used a simple hierarchical structure like this:
class Window
class Dragable : public Window
class Skinable : public Dragable
class DraggableSkinnableWindow : Skinnable
I still want Dragable and Skinable to be abstract as well but is that even possible? Is the second example even a good solution for the same context but not using MI?
Thank you in advance!
While your example is a solid use case for multiple inheritance, I disagree with the assertion that it does not make sense for Skinnable to have an implementation. Rather, as #devianfan alluded to in his comment, your single inheritance alternative fails to model the conceptual taxonomy.
It is about cross axial classifications. A window is both skinabble and draggable but neither of these qualities are codependent.
Consider that, as suggested by your example domain, your application code consists of a collection of graphical user interface elements. You might want to perform perform operations on subgroups of them based on their capabilities. For example you might manipulate the appearance of all skinnable elements based on some customization. On the other hand, there are probably elements of your GUI which are draggable and should be notified on certain user input events. A window is a good example of something which falls into both categories.
I would probably go like this
class Window
class Draggable : public virtual Window
class Skinnable : public virtual Window
class DraggableSkinnableWindow : Draggable, Skinnable
And provide default implementation in the pure virtual methods contained in Draggabel and Skinnable separately
class Draggable : public virtual Window {
virtual void aMethod() = 0;
void aMethodDefaultImplementation() = { //...// };
}
then inside DraggableSkinnable you have two options:
virtual void aMethod() = { aMethodDefaultImplementation() };
or
virtual void aMethod() = {// ...non-default implementation... //};
This has the benefit of providing a default implementation if you need one (as if aMethod was not pure virtual) but forcing you to ask for that explicitly (because it is purely virtual).
I think this is supposed to be a good example where MI makes sense.
It does, at long as Window, Draggable, Skinnable do not share common ancestor, at least other than pure abstract, otherwise you would need virtual inheritance.
Since it doesn't make sense to implement a class of Skinable, it should be defined abstract.
It can make sense, for example defining a property skin + setters and getters. You seem to be confusing abstract classes and pure abstract classes. Abstract classes have at least one pure virtual function, which means you cannot instantiate them. Pure abstract classes do not have any implementation of any method, they contain only pure virtual functions, and are often used as a realization interface concept in c++.
How would this look like if I would not use the concept of MI. Is the second example even a good solution for the same context but not using MI?
You cannot do it properly. c++ does not differentiate between classes and interfaces (as it does not provide such concept on language level). It is the same as stripping java or c# of interfaces. It would be possible if you provided all the compounds by hand i.e. Skinnable, Draggable bases, would produce SkinnableDraggable and/or DraggableSkinnable (which would probably be equivalent) dervided classes. This is quite a killer.
Your example, as others mentioned completely mixes unrelated concepts. E.g. Your Draggables and Skinnables must be Windowses. This is not obvious, and certainly not correct in general.

Can someone explain the benefits of polymorphism?

So I understand pretty much how it works, but I just can't grasp what makes it useful. You still have to define all the separate functions, you still have to create an instance of each object, so why not just call the function from that object vs creating the object, creating a pointer to the parent object and passing the derived objects reference, just to call a function? I don't understand the benefits of taking this extra step.
Why do this:
class Parent
{
virtual void function(){};
};
class Derived : public Parent
{
void function()
{
cout << "derived";
}
};
int main()
{
Derived foo;
Parent* bar = &foo;
bar->function();
return -3234324;
}
vs this:
class Parent
{
virtual void function(){};
};
class Derived : public Parent
{
void function()
{
cout << "derived";
}
};
int main()
{
Derived foo;
foo.function();
return -3234324;
}
They do exactly the same thing right? Only one uses more memory and more confusion as far as I can tell.
Both your examples do the same thing but in different ways.
The first example calls function() by using Static binding while the second calls it using Dynamic Binding.
In first case the compiler precisely knows which function to call at compilation time itself, while in second case the decision as to which function should be called is made at run-time depending on the type of object which is pointed by the Base class pointer.
What is the advantage?
The advantage is more generic and loosely coupled code.
Imagine a class hierarchy as follows:
The calling code which uses these classes, will be like:
Shape *basep[] = { &line_obj, &tri_obj,
&rect_obj, &cir_obj};
for (i = 0; i < NO_PICTURES; i++)
basep[i] -> Draw ();
Where, line_obj, tri_obj etc are objects of the concrete Shape classes Line, Triangle and so on, and they are stored in a array of pointers of the type of more generalized base class Shape.
This gives the additional flexibility and loose coupling that if you need to add another concrete shape class say Rhombus, the calling code does not have to change much, because it refers to all concrete shapes with a pointer to Base class Shape. You only have to make the Base class pointer point to the new concrete class.
At the sametime the calling code can call appropriate methods of those classes because the Draw() method would be virtual in these classes and the method to call will be decided at run-time depending on what object the base class pointer points to.
The above is an good example of applying Open Closed Principle of the famous SOLID design principles.
Say you want someone to show up for work. You don't know whether they need to take a car, take a bus, walk, or what. You just want them to show up for work. With polymorphism, you just tell them to show up for work and they do. Without polymorphism, you have to figure out how they need to get to work and direct them to that process.
Now say some people start taking a Segway to work. Without polymorphism, every piece of code that tells someone to come to work has to learn this new way to get to work and how to figure out who gets to work that way and how to tell them to do it. With polymorphism, you put that code in one place, in the implementation of the Segway-rider, and all the code that tells people to go to work tells Segway-riders to take their Segways, even though it has no idea that this is what it's doing.
There are many real-world programming analogies. Say you need to tell someone that there's a problem they need to investigate. Their preferred contact mechanism might be email, or it might be an instant message. Maybe it's an SMS message. With a polymorphic notification method, you can add a new notification mechanism without having to change every bit of code that might ever need to use it.
polymorphism is great if you have a list/array of object which share a common ancestor and you wich to do some common thing with them, or you have an overridden method. The example I learnt the concept from, use shapes as and overriding the draw method. They all do different things, but they're all a 'shape' and can all be drawn. Your example doesn't really do anything useful to warrant using polymorphism
A good example of useful polymorphism is the .NET Stream class. It has many implementations such as "FileStream", "MemoryStream", "GZipStream", etcetera. An algorithm that uses "Stream" instead of "FileStream" can be reused on any of the other stream types with little or no modification.
There are countless examples of nice uses of polymorphism. Consider as an example a class that represents GUI widgets. The most base classs would have something like:
class BaseWidget
{
...
virtual void draw() = 0;
...
};
That is a pure virtual function. It means that ALL the class that inherit the Base will need to implement it. And ofcourse all widgets in a GUI need to draw themselves, right? So that's why you would need a base class with all of the functions that are common for all GUI widgets to be defined as pure virtuals because then in any child you will do like that:
class ChildWidget
{
...
void draw()
{
//draw this widget using the knowledge provided by this child class
}
};
class ChildWidget2
{
...
void draw()
{
//draw this widget using the knowledge provided by this child class
}
};
Then in your code you need not care about checking what kind of widget it is that you are drawing. The responsibility of knowing how to draw itself lies with the widget (the object) and not with you. So you can do something like that in your main loop:
for(int i = 0; i < numberOfWidgets; i++)
{
widgetsArray[i].draw();
}
And the above would draw all the widgets no matter if they are of ChildWidget1, ChildWidget2, TextBox, Button type.
Hope that it helps to understand the benefits of polymorphism a bit.
Reuse, generalisation and extensibility.
I may have an abstract class hierarchy like this: Vehicle > Car. I can then simply derive from Car to implement concrete types SaloonCar, CoupeCar etc. I implement common code in the abstract base classes. I may have also built some other code that is coupled with Car. My SaloonCar and CoupeCar are both Cars so I can pass them to this client code without alteration.
Now consider that I may have an interface; IInternalCombustionEngine and a class coupled with with this, say Garage (contrived I know, stay with me). I can implement this interface on classes defined in separate class hierarchies. E.G.
public abstract class Vehicle {..}
public abstract class Bus : Vehicle, IPassengerVehicle, IHydrogenPowerSource, IElectricMotor {..}
public abstract class Car : Vehicle {..}
public class FordCortina : Car, IInternalCombustionEngine, IPassengerVehicle {..}
public class FormulaOneCar : Car, IInternalCombustionEngine {..}
public abstract class PowerTool {..}
public class ChainSaw : PowerTool, IInternalCombustionEngine {..}
public class DomesticDrill : PowerTool, IElectricMotor {..}
So, I can now state that an object instance of FordCortina is a Vehicle, it's a Car, it's an IInternalCombustionEngine (ok contrived again, but you get the point) and it's also a passenger vehicle. This is a powerful construct.
The poly in polymorphic means more than one. In other words, polymorphism is not relevant unless there is more than one derived function.
In this example, I have two derived functions. One of them is selected based on the mode variable. Notice that the agnostic_function() doesn't know which one was selected. Nevertheless, it calls the correct version of function().
So the point of polymorphism is that most of your code doesn't need to know which derived class is being used. The specific selection of which class to instantiate can be localized to a single point in the code. This makes the code much cleaner and easier to develop and maintain.
#include <iostream>
using namespace std;
class Parent
{
public:
virtual void function() const {};
};
class Derived1 : public Parent
{
void function() const { cout << "derived1"; }
};
class Derived2 : public Parent
{
void function() const { cout << "derived2"; }
};
void agnostic_function( Parent const & bar )
{
bar.function();
}
int main()
{
int mode = 1;
agnostic_function
(
(mode==1)
? static_cast<Parent const &>(Derived1())
: static_cast<Parent const &>(Derived2())
);
}
Polymorphism is One of the principles OOP. With polymorphism you can choose several behavior in runtime. In your sample, you have a implementation of Parent, if you have more implementation, you can choose one by parameters in runtime. polymorphism help for decoupling layers of application. in your sample of third part use this structers then it see Parent interface only and don't know implementation in runtime so third party independ of implementations of Parent interface. You can see Dependency Injection pattern also for better desing.
Just one more point to add. Polymorphism is required to implement run-time plug-ins. It is possible to add functionality to a program at run-time. In C++, the derived classes can be implemented as shared object libraries. The run time system can be programmed to look at a library directory, and if a new shared object appears, it links it in and can start to call it. This can also be done in Python.
Let's say that my School class has a educate() method. This method accepts only people who can learn. They have different styles of learning. Someone grasps, someone just mugs it up, etc.
Now lets say I have boys, girls, dogs, and cats around the School class. If School wants to educate them, I would have to write different methods for the different objects, under School.
Instead, the different people Objects (boys,girls , cats..) implement the Ilearnable interface. Then, the School class does not have to worry about what it has to educate.
School will just have to write a
public void Educate (ILearnable anyone)
method.
I have written cats and dogs because they might want to visit different type of school. As long as it is certain type of school (PetSchool : School) and they can Learn, they can be educated.
So it saves multiple methods that have the same implementation but different input types
The implementation matches the real life scenes and so it's easy for design purposes
We can concentrate on part of the class and ignore everything else.
Extension of the class (e.g. After years of education you come to know, hey, all those people around the School must go through GoGreen program where everyone must plant a tree in the same way. Here if you had a base class of all those people as abstract LivingBeings, we can add a method to call PlantTree and write code in PlantTree. Nobody needs to write code in their Class body as they inherit from the LivingBeings class, and just typecasting them to PlantTree will make sure they can plant trees).

How to: derived member in derived class with derived class specific methods

I am using C++ under Ubuntu 11.10 and the latest version of NetBeans. Let's say I have the
following code:
class Node {}
class DerivedNode : public Node {}
class Graph {
vector<Node*> nodes;
}
class DerivedGraph : public Graph { }
At the moment I'm storing DerivedNodes in the DerivedGraph class like this for example:
nodes.push_back(new DerivedNode());
When I need to use specific methods that only apply to DerivedNodes and DerivedGraphs
I am forced to use a dynamic_cast on my Node pointers first.
I would like to be able to have specific methods in DerivedGraph which apply only to DerivedNodes
and avoid the need of casting pointers. I do not mind having to redesign my classes if the end
result is better than what I have.
I am sure there must be a clean and simple method to achieve the same thing I'm trying to do.
Maybe something with specialized templates? Any thoughts on the matter would be greatly
appreciated. I'll also provide any additional information required in the case I haven't been too
clear.
EDIT: I don't have two copies. I wanted to put emphasis on how it looks. I apologize for the presentation. What I want to obtain is:
class DerivedGraph: public Graph {
vector<DerivedNode*> nodes;
}
Are you sure that your interface in Node is appropriate? Sometimes when you find yourself needing to downcast (especially in a case like this where base pointers are stored in a container) that may be a signal that your abstract interface doesn't cover all your needs properly. Often something like the Template Method pattern solves all your needs without needing a downcast at all.
However, assuming that your inheritance model really need work in such a way, what you probably want to do is have virtual methods that get overridden in DerivedGraph for adding and getting nodes. You will have to verify the node type and downcast it in this case.
One final approach is to have two separate containers, one in the parent that contains all nodes that aren't DerivedNode and then another container in DerivedGraph that contains all the DerivedNode. Then you use overridden functions again to determine which container to access depending on your API needs.
Start by not duplicating your data member in the derived class.
Then add virtual member functions that you use to add data to your container. That way you can create instances of derived types in the derived class and add them to the container.
Finally, when you override the virtual function that returns a reference to data in the derived class, use covariant return types.

How can I structure my C++ code so that I only write my common methods once?

If C++.NET allowed multiple inheritance, I would have my common methods in a class and derive from it.
I have classes derived from Panel, Label, TabControl ... which have the same methods exactly.
How can I structure my C++ code so that I only write my common methods once?
Here is a simple example of a property I want to add to each derived class. Extension methods sound ideal, but don't exist in C++.
private: int panelBottomMargin;
public:
[Browsable(true)]
[CategoryAttribute("Layout"), DescriptionAttribute(
"Specify the gap between the last control and the bottom of the panel"),
DefaultValueAttribute(panelBottomMarginDefault)]
[DesignerSerializationVisibility(DesignerSerializationVisibility::Visible)]
property int PanelBottomMargin
{
int get() { return this->panelBottomMargin; }
void set(int margin) { this->panelBottomMargin = margin; }
}
I can't quite make out for sure what you mean by "common methods" here, but generally speaking namespace level non-member functions are the best way to do that (see pretty much every algorithm in the standard library).
If it actually needs access to private attributes of your class then it's probably not a common method and should be implemented in the level of inheritance where the attribute it operates on exist.
It's almost certainly an abuse of inheritance to put common methods into a class that you then inherit from: Use inheritance to extend, NOT to reuse.
Put your common methods in a Utility class, create an instance of this class (pass the object to work on to the constructor) when needed.
What is wrong with static methods? Or instantiating a new class which can operate on objects of the type given? Its best to not abuse inheritance in ways which clearly don't follow the "is-a" doctrine - use "has-a" whenever possible.
Generally, if MI is being considered as a solution to your problem which does not involve "mixin" type semantics, you should consider a new solution.
You could use .NETs "extension methods" if you don't need to access private/protected fields of an object.

Factory Pattern in C++ -- doing this correctly?

I am relatively new to "design patterns" as they are referred to in a formal sense. I've not been a professional for very long, so I'm pretty new to this.
We've got a pure virtual interface base class. This interface class is obviously to provide the definition of what functionality its derived children are supposed to do. The current use and situation in the software dictates what type of derived child we want to use, so I recommended creating a wrapper that will communicate which type of derived child we want and return a Base pointer that points to a new derived object. This wrapper, to my understanding, is a factory.
Well, a colleague of mine created a static function in the Base class to act as the factory. This causes me trouble for two reasons. First, it seems to break the interface nature of the Base class. It feels wrong to me that the interface would itself need to have knowledge of the children derived from it.
Secondly, it causes more problems when I try to re-use the Base class across two different Qt projects. One project is where I am implementing the first (and probably only real implementation for this one class... though i want to use the same method for two other features that will have several different derived classes) derived class and the second is the actual application where my code will eventually be used. My colleague has created a derived class to act as a tester for the real application while I code my part. This means that I've got to add his headers and cpp files to my project, and that just seems wrong since I'm not even using his code for the project while I implement my part (but he will use mine when it is finished).
Am I correct in thinking that the factory really needs to be a wrapper around the Base class rather than the Base acting as the factory?
You do NOT want to use your interface class as the factory class. For one, if it is a true interface class, there is no implementation. Second, if the interface class does have some implementation defined (in addition to the pure virtual functions), making a static factory method now forces the base class to be recompiled every time you add a child class implementation.
The best way to implement the factory pattern is to have your interface class separate from your factory.
A very simple (and incomplete) example is below:
class MyInterface
{
public:
virtual void MyFunc() = 0;
};
class MyImplementation : public MyInterface
{
public:
virtual void MyFunc() {}
};
class MyFactory
{
public:
static MyInterface* CreateImplementation(...);
};
I'd have to agree with you. Probably one of the most important principles of object oriented programming is to have a single responsibility for the scope of a piece of code (whether it's a method, class or namespace). In your case, your base class serves the purpose of defining an interface. Adding a factory method to that class, violates that principle, opening the door to a world of shi... trouble.
Yes, a static factory method in the interface (base class) requires it to have knowledge of all possible instantiations. That way, you don't get any of the flexibility the Factory Method pattern is intended to bring.
The Factory should be an independent piece of code, used by client code to create instances. You have to decide somewhere in your program what concrete instance to create. Factory Method allows you to avoid having the same decision spread out through your client code. If later you want to change the implementation (or e.g. for testing), you have just one place to edit: this may be e.g. a simple global change, through conditional compilation (usually for tests), or even via a dependency injection configuration file.
Be careful about how client code communicates what kind of implementation it wants: that's not an uncommon way of reintroducing the dependencies factories are meant to hide.
It's not uncommon to see factory member functions in a class, but it makes my eyes bleed. Often their use have been mixed up with the functionality of the named constructor idiom. Moving the creation function(s) to a separate factory class will buy you more flexibility also to swap factories during testing.
When the interface is just for hiding the implementation details and there will be only one implementation of the Base interface ever, it could be ok to couple them. In that case, the factory function is just a new name for the constructor of the actual implementation.
However, that case is rare. Except when explicit designed having only one implementation ever, you are better off to assume that multiple implementations will exist at some point in time, if only for testing (as you discovered).
So usually it is better to split the Factory part into a separate class.