Root base class in C++ - c++

Every object in .NET inherits (directly or indirectly) from the common root base "Object". Is there such a common object root in C++? How do I pass any object to a function?
public void DoSomeStuff(object o) { ... }
EDIT: To clarify, the purpose: In that function I want to invoke a pointer to member function. For that I need the object instance and pointer to the required function. To simplify readability I want to make a wrapper containing the both required information. I'm not sure if that is the best way, but it is the background idea.

There is no common base class; but using a something like boost::any or more generally a template based approach is preferred over a void*.

There is no common root class. Use either void* to pass any object into a function, or better define some base class.

Template functions are present and avoid the need for such root parent of all classes.
template <class T>
void DoSomeStuff(T const &t) {
// Do the stuff with t...
t.callTheFunction();
}
If all your objects have a member function callTheFunction(), then you got the exactly same behavior than having a root base class, with the same requirement (all your classes have a function with that name).
In addition, you got the additional benefit of being able to specialize the template function DoSomeStuff() for some classes that are not yours, and could not inherit your virtual member function.

For that I need the object instance and pointer to the required function.
That sounds a lot like "delegates". First, you definitely will need to define a common base class for all the objects that you want to call. In C++ you can use multiple inheritance if the object already belong to some other hierarchy.
Then have a read through Member Functions and the Fastest Possible C++ Delegates which is an excellent in-depth article on the topic of delegates (which are an object and member function pointer bound together). Using the header file described in that article, you can create delegates and easily call them just like regular function pointers.

Sorry - there is no root base object in C++. But you can define your own for all your classes.

There is no common base class in C++. However, there are already libraries that allow you to call member functions as delegates. You can try using boost::function together with boost::bind or boost::lambda.

You'd at least depend on a minimum c++ runtime if there were a root object implemented in c++. This is undesirable sometimes.

Related

c++ template class member specialization and inheritance

I would like to write down a set of classes in which there are:
a pure virtual class that wraps an object of any kind and the relate getter for it.
one or more classes for every kind of object I need, extending the virtual one and overriding the getter in order to specialize it.
A template class solution for the wrapper seems to fit the case but I have to use it in two different contexts:
the first one is not aware of wrapper implementations. In this case I should declare a Wrapper<AnyObj> var; with AnyObj standing for any class name (like ? in Java). As far as I know, you can't do this in c++.
the second one is restricted to a particular wrapper implementation. In this case I need the getter to return the wrapped object with the exact type (rather than downcasting it).
If I'm right I cannot use a template class and, moreover, the wrapper won't have a protected: T* wrappedObject member.
I don't know if I'm stuck in the Java approach, wrongly thinking from the beginning, or missing something.
Any suggestion is appreciated.

C++ design issue. New to templates

I'm fairly new to c++ templates.
I have a class whose constructor takes two arguments. It's a class that keeps a list of data -- it's actually a list of moves in a chess program.
I need to keep my original class as it's used in other places, but I now need to pass extra arguments to the class, and in doing so have a few extra private data members and specialize only one of the private methods -- everything else will stay the same. I don't think a derived class helps me here, as they aren't going to be similar objects, and also the private methods are called by the constructor and it will call the virtual method of the base class -- not the derived method.
So I guess templates are going to be my answer. Just looking for any hints about how might proceed.
Thanks in advance
Your guess is wrong. Templates are no more the answer for your problem than inheritance is.
As jtbandes said in comment below your question, use composition.
Create another class that contains an instance of your existing class as a member. Forward or delegate operations to that contained object as needed (i.e. a member function in your new class calls member functions of the contained object). Add other members as needed, and operations to work with them.
Write your new code to interact with the new class. When your new code needs to interact with your old code, pass the contained object (or a reference or a pointer to it) as needed.
You might choose to implement the container as a template, but that is an implementation choice, and depends on how you wish to reuse your container.
Templates are used when you want to pass at compile time parameter like values,typenames, or classes. Templates are used when you want to use exactly the same class with the same methods, but applying it to different parameters. The case you described is not this I think.
If they aren't goign to be similar objects you may want to create a specialized class (or collections of function) to use from the various other classes.
Moreover you can think of creating a base class and extending it as needed. Using a virtual private method should allow you to select the method implementation of the object at runtime instead of the method of the base class.
We may help you more if you specify what does they need to share, what does your classes have in common?
The bare bones of my present code looks like this:
class move_list{
public:
move_list(const position& pos, unsigned char ply):pos_(pos),ply_(ply){
//Calculates moves and calls add_moves(ply,target_bitboard,flags) for each move
}
//Some access functions etc...
private:
//private variables
void add_moves(char,Bitboard,movflags);
};
Add_moves places the moves on a vector in no particular order as they are generated. My new class however, is exactly the same except it requires extra data:
move_list(const position& pos, unsigned char ply,trans_table& TT,killers& kill,history& hist):pos_(pos),ply_(ply),TT_(TT),kill_(kill),hist_(hist) {
and the function add_moves needs to be changed to use the extra data to place the moves in order as it receives them. Everything else is the same. I guess I could just write an extra method to sort the list after they have all been generated, but from previous experience, sorting the list as it receives it has been quicker.

c++ polymorphism and list

struct struct_unit{};
struct struct_unit_rotable : struct_unit {};
std::list <struct_unit> unitsList;
struct_unit *su=new struct_unit_rotable;
unitsList.push_front(*su);
then i have 2 draw methods:
void drawUnit(struct_unit &su);
void drawUnit(struct_unit_rotable &su);
when i call drawUnit(unitsList.front()); --- the WRONG nonrotable draw method is called
how to correctly insert
struct_unit_rotable type into list so the unitsList.front() will return type struct_unit_rotable?
You misunderstand polymorphism. The idea of polymorphism is to allow derived classes to provide implementations for methods declared virtual in a base class, but use pointer or reference to base class to access that implementation (if you use the objects directly, they will get sliced, see David's answer). In your case, there are no such declarations and hence no polymorphism.
To invoke polymorphism you would need
struct unit
{
virtual void draw();
virtual ~unit(); // important
};
struct unit_rotatable // did you really mean 'rotable'?
: unit
{
virtual void draw(); // 'virtual' needed only for another level of polymorphism
virtual ~unit_rotatable();
}
and invoke them via
std::list <std::unique_ptr<unit>> unitsList; // we need pointer (or reference) to base
unitList.emplace_front(new unit_rotatable);
unitList.front()->draw(); // calls unit_rotatable::draw()
I used unique_ptr to ensure the automatic de-allocation of the objects at the destruction of unitsList.
Your list will contain objects of type struct_unit. If you pass it objects of type struct_unit_rotable they will get sliced
Even if you use pointers only void drawUnit(struct_unit *su) will get called, you need to put the polymorphism into the structures as Walter has shown
as long as you insert the object as struct_unit, you'll always get this kind of object back and your drawUnit function called will always be the one for struct_unit. Aren't you able to move the drawUnit() function inside the object and make a class ? If you make the function virtual, you can have the correct one called.
This is quite an odd use of polymorphism.
A better way would be a virtual drawUnit() in struct_unit that will be overridden in struct_unit_rotable.
I do not have the standard at hand but I am sure that there is no proper way without casting to detect the most appropriate method as for the vector content it is of type struct_unit.
See here for a related issue: Matching an overloaded function to its polymorphic argument
It is stated that overload resolution is done at compile time. Your code would require overload resolution during execution time as it is not clear what type would be placed in the vector during compile time.
I see what you're trying to do. There is a very slick way to do this, introduced in this video which I would recommend anyone to study.
http://channel9.msdn.com/Events/GoingNative/2013/Inheritance-Is-The-Base-Class-of-Evil
[Inheritance Is The Base Class of Evil][1]
The basic premise here is that "inheritance should be an implementation detail, not an interface".
The more I have worked this way, the happier I have been that I have done so.

C++ inheritance pattern

I am after your opinion on how best to implement an inheritance pattern in C++. I have two base classes, say
class fooBase{
protected:
barBase* b;
};
class barBase{};
where fooBase has a barBase. I intend to put these classes in a library, so that wherever I have a fooBase it can use its barBase member.
I now intend to create a specialisation of these in a specific program
class fooSpec : public fooBase{};
class barSpec : public barBase{};
Now I want fooSpec::b to point to a barSpec instead of a barBase. I know that I can just initialise b with a new barSpec, but this would require me to cast the pointer to a barSpec whenever I wanted to use specific functions in the specialisation wouldn't it?
Is there another way that this is often acheived?
Cheers.
Create a method in your specclass to cast the b into the special version.
That way instead of casting it all the time, it looks like a getter.
On the other hand OO is about programming towards interfaces and not objects. So what you are doing here looks like programming towards objects. But the is difficult to see as this example is purely theoretical.
You may consider the template solution:
template <class T>
class fooBase{
protected:
T* b;
};
and then use it as
class fooSpec : public fooBase<barSpec>{};
while ordinarily, the base would be used as fooBase<barBase>.
Is this what you want?
Normally we create a function that has the cast and returns the pointer -- and use that instead of the member directly.
Now I want fooSpec::b to point to a barSpec instead of a barBase.
There's no such thing as fooSpec::b. b belongs to fooBase, and your new class fooSpec is a (specialization of) a fooBase. You can't change the fact that b, a fooBase member, is of type barBase. This is a property of all the instances of fooBase that you can't invalidate in the particular subset of instances concerned by your specialization.
I know that I can just initialise b with a new barSpec, but this would
require me to cast the pointer to a barSpec whenever I wanted to use
specific functions in the specialisation wouldn't it?
Yes and no. Yes, you need to do that cast; but no, you don't need to do it every time. You can encapsulated in a function of fooSpec.
Is there another way that this is often acheived?
Not that I'm aware of.
this would require me to cast the pointer to a barSpec whenever I wanted to use specific functions in the specialisation wouldn't it?
That depends on whether the method you are trying to invoke is defined in the superclass and whether it is virtual.
You need to cast the pointer before invoking a method if one of the following is true...
The method belongs to the subclass only
The superclass has an implementation of the method and the subclass's implementation does not override the implementation in the superclass. This amounts to a question of whether the function is a virtual function.
Avoid data members in non-leaf classes, use pure virtual getters instead. If you follow this simple rule, your problem solves itself automatically.
This also makes most non-leaf classes automatically abstract, which may seem like an undue burden at first, but you get used to it and eventually realize it's a Good Thing.
Like most rules, this one is not absolute and needs to be broken now and then, but in general it's a good rule to follow. Give it a try.
If it looks too extreme, you may try one of the design patterns that deal with dual hierarchies such as Stairway to Heaven.

Is there a way to determine at runtime if an object can do a method in C++?

In Perl, there is a UNIVERSAL::can method you can call on any class or object to determine if it's able to do something:
sub FooBar::foo {}
print "Yup!\n" if FooBar->can('foo'); #prints "Yup!"
Say I have a base class pointer in C++ that can be any of a number of different derived classes, is there an easy way to accomplish something similar to this? I don't want to have to touch anything in the other derived classes, I can only change the area in the base class that calls the function, and the one derived class that supports it.
EDIT: Wait, this is obvious now (nevermind the question), I could just implement it in the base that returns a number representing UNIMPLEMENTED, then check that the return is not this when you call it. I'm not sure why I was thinking of things in such a complicated manner.
I was also thinking I would derive my class from another one that implemented foo then see if a dynamic cast to this class worked or not.
If you have a pointer or reference to a base class, you can use dynamic_cast to see which derived class it is (and therefore which derived class's methods it supports).
If you can add methods to the base class, you can add a virtual bool can_foo() {return false;} and override it in the subclass that has foo to return true.
C++ does not have built in run-time reflection. You are perfectly free to build your own reflection implementation into your class hierarchy. This usually involves a static map that gets populated with a list of names and functions. You have to manually register each function you want available, and have consistency as to the calling convention and function signature.
I believe the most-correct way would be to use the typeid<> operator and get a reference to the type_info object, and then you could compare that (== operator) to the desired type_info for the data types you wish to care about.
This doesn't give you method-level inspection, and does require that you've built with RTTI enabled (I believe that using typeid<> on an object that was built without RTTI results with "undefined" behavior), but there you are.
MSDN has an online reference to get you started : http://msdn.microsoft.com/en-us/library/b2ay8610%28VS.80%29.aspx