C++, abstract class and inheritance - c++

I'm trying to process classes instance two by two.
I have a abstract base class (IBase here) that contains a doStuff method.
This method will be overriden in extended class in order to process all other defined classes.
This is part of a library I'm building. I want Base objects to be written by the library user. Each Base class need to interact with another Base objects through the doStuff methode. The container is needed to handle multiples Base objects.
It is not the first time I run into this problem, but I can't remember how I did the last times. This kind of class can be used for a lot of thing. Here, it is a collision detection system. IBase represent an abstract HitBox and Container represente the Scene where collision occures. In this case, Container::process checks for transitions between hit boxes and Container::process is used to implement the optimizing algorithm (quadtree, ...).
I built those class in this way:
class IBase {
public:
virtual void doStuff(IBase* base) = 0;
}
class Base {
public:
virtual void doStuff(Base* base) {
foobar();
}
virtual void doStuff(IBase* base) {
// irrelevant
}
}
class Container {
public:
void process() {
for (std::list<IBase*>::iterator it=base_list.begin() ; it!=base_list.end() ; it++) {
for (std::list<IBase*>::itarator jt=std::next(it) ; jt!=base_list.end() ; jt++) {
(*it)->doStuff(*jt);
}
}
}
private:
std::list<Ibase*> base_list;
}
But in the loop, I can't reach void Base::doStuff(Base*) when working with two Base objects.
I can only call Base::doStuff(IBase*) which is not something I want.
Any help on this one ? I understand the problem, but I can't see a solution to it. Is this the good way to handle it or do I need to think again my architecture ? How would you do this ? I think a design pattern must exists for such a problem, but I didn't find any that fits.
Thanks

C++ does not support contravariance for arguments. See also Why is there no parameter contra-variance for overriding?.
You might be better off explicitly invoking doStuff(Base* base) from within the doStuff(IBase* base) body.

Your objects, when dereferenced from *it and *jt, are referenced as IBase objects, not Base objects. This means that only methods from IBase can be called.
Your virtual method:
virtual void doStuff(Base* base) { ... }
is not overriding anything. It is creating a new virtual method that is accessible from Base downward only. When you call doStuff from a IBase pointer, it's going to call:
virtual void doStuff(IBase* base) { ... }
which matches the signature defined in IBase.
If you want to execute your foobar function, you should do some kind of check on base when it's based into the overriding doStuff, cast it to Base* once you're sure it's safe, then work with it as needed.
virtual void doStuff(IBase* base) {
// not irrelevant
if (base->isBase())
{
foobar();
}
}
And finally, as previously suggested, make doStuff public.

Related

using virtual function vs dynamic_cast

Instead of using a virtual function, is it fine to use something like:
void BaseClass::functionName () { // BaseClass already has virtual functions
// some LONG code true for all derived classes of BaseClass
// ...
if (typeid (*this) == typeid (DerivedClass1))
// use functions of DerivedClass1 on dynamic_cast<DerivedClass1*>(this)
else if (typeid (*this) == typeid (DerivedClass2))
// use functions of DerivedClass2 on dynamic_cast<DerivedClass2*>(this)
// some LONG code true for all derived classes of BaseClass
// ...
}
It's just that I feel it's not a good idea to use virtual functions for something like the above when it is only a small section that is specialized for the derived classes. The long code that is used for all the derived classes will then need to be used over and over for all the derived classes (suggesting a helper function(s) just for that). Of course, I've tested my method and it works (and I suppose with no loss in performance), but I wonder if this is questionable practice.
What if the if-else-if part is used more than once in the function?
And if the common code for all derived classes is relavitively SHORT, then it is better to use virtual functions then, right?
Why not do this:
void BaseClass::functionName () {
// some LONG code true for all derived classes of BaseClass
// ...
this->some_protected_virtual_member_function();
// some LONG code true for all derived classes of BaseClass
// ...
}
So the common part is not duplicated and the behavior can still easily have extensions in your children classes without having to add another if to your parent class
Your code will not work at all unless the classes have virtual functions. C++ provides only limited reflection: typeid(DerivedClass1)==typeid(DerivedClass2) if there are no virtual functions. The above code also may be slower than simply accessing a virtual function: you'll get a new branch for each type rather than a constant time pointer lookup.
However, the biggest issue with the above code is that it looses polymorphism and encapsulation. The using code must be aware or what DerivedClass1 and DerivedClass2 need to do. It needs to be aware of the structures inside DerivedClass1 and DerivedClass2. Also, all the code is piled into one place, making this function possibly hundreds of lines.
I think you're looking for the template method pattern here: Just use your existing non-virtual function and have it call a virtual function only for the small section of code that differes between concrete classes. It has the advantage of looking prettier too.
void BaseClass::functionName () {
// some LONG code true for all derived classes of BaseClass
// ...
functionName_impl(); // Will be virtual (private or protected) and overriden in each child class to do the right work.
// some LONG code true for all derived classes of BaseClass
// ...
}
This is a degenerate case of the Template Method Pattern:
class Base {
public:
void templated() {
// do some stuff
this->hook1();
// other stuff
if (/*cond*/) { this->hook2(); }
size_t acc = 0;
for (Stuff const& s: /*...*/) { acc += this->hook3(s); }
// other stuff
}
private:
virtual void hook1() {}
virtual void hook2() {}
virtual size_t hook3(Stuff const&) { return 0; }
}; // class Base
And then a Derived class can customize the behavior of the hooks.
A word of warning: this is extremely rigid, by nature, since the templated method is not virtual; this is a both a virtue and a problem of this pattern, it is good because if you need to change the templated method then it is defined in a single place and it is annoying if the hooks provided are not sufficient to customize the behavior.

Require override of parent virtual function

I'm working on a serialization system, and all my serializable classes implement
virtual void serialize(Buffer buffer);
When a pointer is going to be serialized, I need to call the serialize() function of the class itself, and not that of any of its parents, even if the pointer is a parent type, and I've been running into a lot of bugs because I don't notice that a child class doesn't even have serialize() at all so the parent serialize() class is just being called
ie
class A
{
virtual void serialize();
}
class B:public A
{
virtual void serialize();
}
class C:public B
{
virtual void serialize();
}
void doSerialization(A *a)
{
a->serialize();
}
C *c=new C();
doSerialization(c);
right now, if C didn't have a serialize function, B::serialize() would be silently called. I'd prefer an error message, or anything else that will at least point it out to me. Is there any keyword in C++ (even '11) that would do this?
There's no easy way of doing so in C++.
There is a hack though, explained in this answer, using virtual inheritance and forcing your classes to register which serialize method they are using.
Use pure virtual function in parent:
virtual void serialize(Buffer buffer) = 0;
At compile time you can only do that by making the function a pure virtual function in classes that are not final:
class A
{
virtual void serialize() = 0;
}
class B:public A
{
virtual void serialize() = 0;
}
class C final:public B
{
virtual void serialize();
}
Of course that means that all concrete classes in your design need to be final. If you must inherit from concrete classes, you can't enforce this at compile time.
right now, if C didn't have a serialize function B::serialize() would be silently called.
No, you'll get linker error. As I see, that's what you want.
One variant to solve this is is to not inherit several layers, so instead of class C: public B, you use class C: public A. Of course, that's not necessarily a suggestion for all scenarios.
At some point sooner or later, you do have to leave things in the hand of the programmer.
There may be some ways to check this as well, - maybe create a temporary pointer to B and check if typeid(*this) == typeid(temp) or some such?

concept of virtual functions in c++?

I read so many blogs and I understand how to use virtual function in c++. But, still I don't understand why we use virtual functions. Can you give me a real world example so that I can more easily visualize the actual meaning of virtual function.
An important thing to mention is that inheritance (which the keyword virtual is fundamental for) should not be for the sole purpose of code re-use, use delegation for this.
Delegation would be when we have a class say BroadbandConnection with a method called connection(). Then your manager says we want to add encryption, so you create a class BroadbandConnectionWithEncryption. Your natural instinct may be to use inheritance and then make the new class BroadbandConnectionWithEncryption derive from BroadbandConnection.
Drawback's to this is that the creator of the initial class had not designed it for inheritance so you would need to change its definition to make the method connection() virtual so you can override its behavior in the derived class. This is not always ideal. A better idea is to use delegation here for the purpose of code reuse.
class BroadBandConnection
{
public:
void Connection (string password)
{
//connection code.
}
};
class BroadBandConnectionWithEndcryption
{
public:
void Connection (string password)
{
mbroadbandconnection.Connection(password);
//now do some stuff to zero the memory or
//do some encryption stuff
}
private:
BroadBandConnection mbroadbandconnection;
};
The keyword virtual is used for the purpose of polymorphism. As the name suggest, it is the ability for an object to have more than one form. This sort of decision would be made at the time of designing an interface or class.
class IShape
{
virtual void Draw () = 0;
};
class Square
{
void Draw()
{
//draw square on screen
}
};
class Circle
{
void Draw()
{
//draw circle on screen
}
};
I made Draw() pure virtual with the = 0. I could have left this out and added some default implementation. Pure virtual makes sense for Interfaces where there is no reasonable default implementation.
What this lets me do is pass around a Shape object to various methods and they do not need to be concerned with what I have just given them. All they know is that I have to provide something that supports the ability for a shape to draw itself.
IShape* circle = new Circle ();
IShape* square = new Square ();
void SomeMethod (IShape* someShape)
{
someShape->Draw(); //This will call the correct functionality of draw
}
In the future as people begin thinking of new shapes, they can derive from IShape and so long as they implement some functionality for Draw. They can pass this object to SomeMethod.
First, this.
Now, a real life example. I have a program with a GUI with three tabs. Each tab is an object of a class that derives from a common base, TabBase. It has a virtual function OnActivate(). When a tab is activated, the dispatcher calls it on the current tab. There's some common action and there are actions that are specific to this tab. This is implemented via virtual functions.
The benefit is that the controller does not need to know what kind of tab it is. It stores an array of TabBase pointers, and just calls OnActivate() on them. The magic of virtual functions makes sure the right override is called.
class TabBase
{
virtual void OnActivate()
{
//Do something...
}
};
class SearchTab: public TabBase
{
void OnActivate() //An override
{
TabBase::OnActivate(); //Still need the basic setup
//And then set up the things that are specific to the search tab
}
}
We have one base class (animal) that have method, that can be implemented differently by it's children (say). When we declare this method virtual, we can adress that method and it will be implemented from it's children's definition. You don't have to use virtual if you adress children's overloaded methods, but you have to, when you adress parent's methods.
For example, if you have a vector of animals each one of whom is different. You declare method (say) as virtual and call it from animal class and it will be called from corresponding child.
Correct me if I'm wrong, that's how I understood it.
They actually give an example on Wiki
http://en.wikipedia.org/wiki/Virtual_function
using animals. Animals is the super class, all animals eat (the superclass virtual function). Each animal may eat differently than all the other animals (overriding the virtual function). I have a list of arbitrary animals, and when I call the eat function, they will display their own differing eating habit.
If you are familiar with Java - that should be easy. In Java, ALL class methods are effectively virtual. If you override it in a derived class, and you call it via a base class reference, the override will be called, not the base.
That's not the default behavior in C++. If you want a function to behave in that way, you have to declare it as virtual in the base class. Easy enough.
Java is choke full of virtual functions. It just does not have an explicit keyword for them.
The purpose of virtual functions is to achieve dynamic dispatch.
You say you are familiar with Java, so then for a real world use of virtual functions, think of any place in Java where you would have used an interface or used #Override on a public/protected method.
The decision to use virtual functions is a simple matter. You just need to know when you'd want to override a base method. Take the following code as an example:
class animal
{
public:
void sound()
{
cout << "nothing";
}
};
class bird : public animal
{
public:
void sound()
{
cout << "tweet";
}
};
In this case, I'd want to override bird(). But what if I didn't? This is what would happen:
animal * a = new bird;
a->sound();
**Output**
nothing
The screen would say nothing because for all intents and purposes, C++ only sees an animal. However, if you declared it virtual, it knows to search for the lowest method in the class hierachy. Try it again:
class animal{
public:
virtual void sound(){cout<<"nothing";}
};
class bird : public animal
{
public:
void sound()
{
cout << "tweet";
}
};
animal * a = new bird;
a->sound();
**Output**
tweet.
Hope this helps.

Getting OOP right

Ok, this is my problem. I have the following classes:
class Job {
bool isComplete() {}
void setComplete() {}
//other functions
};
class SongJob: public Job {
vector<Job> v;
string getArtist() {}
void setArtist() {}
void addTrack() {}
string getTrack() {}
// other functions
};
// This were already implemeted
Now I want to implement a VideoJob and derived it from Job. But here is my problem. I also have the following function witch it was set to work only with SongJob:
void process(SongJob s)
{
// not the real functions
s.setArtist();
..............
s.getArtist();
.............
s.getArtist();
...............
s.setArtist()
}
Here I just want it to show that the function uses only derived object methods. So if I have another object derived from Job, I will need to change the parameter to Job, but then the compiler would not know about thoose functions and I dont what to test for everyone what kind of object it is and then cast it so I can call the correct function.
So it is okay to put all the functions in the base class, because then I will have no problem, but I don't know if this is correct OOP, if one class deals with Songs and the other with videos, I thing good oop means to have 2 clases.
If I didn't make myself clear, please say so and I will try explaining better.
And in short words, I want to use polymorfism.
It is totally fine to put all the things that the classes SongJob and VideoJob have in common into a common base-class. However, this will cause problems once you want to add a subclass of Job that has nothing to do with artists.
There are some things to note about the code you have posted. First, your class Job is apparently not an abstract base class. This means that you can have jobs that are just jobs. Not SongJob and not VideoJob. If you want to make it clear that there can not be a simple Job, make the base-class abstract:
class Job {
virtual bool isComplete() = 0;
virtual void setComplete() = 0;
//other functions
};
Now, you cannot create instances of Job:
Job job; // compiler-error
std::vector<Job> jobs; // compiler-error
Note that the functions are now virtual, which means that subclasses can override them. The = 0 and the end means that subclasses have to provide an implementation of these functions (they are pure virtual member functions).
Secondly, your class SongJob has a member std::vector<Job>. This is almost certainly not what you want. If you add a SongJob to this vector, it will become a normal Job. This effect is called slicing. To prevent it, you'd have to make it a std::vector<Job*>.
There is much more to say here, but that would go to far. I suggest you get a good book.
In your Base class Job you could add those methods as virtual methods so that a class deriving from Job may or may not override these specific methods.
In your SongJob class you override the methods and dont override them in VideoJob
In, void process() pass a pointer to Base class Job
void process(Job *s)
It will then call the appropriate methods depending on the adress of the objec s is pointing to which will be a SongJob object.
In C++, you have to do two things to get polymorphism to work:
Access polymorphic functions by a reference (&) or pointer (*) to a base type
Define the polymorphic functions as virtual in the base type
So, change these from:
class Job {
bool isComplete() {}
void setComplete() {}
};
void process(SongJob s)
{
// ...
}
To:
class Job {
public: // You forgot this...
virtual bool isComplete() { }
virtual void setComplete() { }
};
void process(Job& s)
{
// ...
}
If you can't define all the functionality you need inside process on your base class (if all the member functions you'd want don't apply to all the derived types), then you need to turn process into a member function on Job, and make it virtual:
class Job {
public:
virtual bool isComplete() { }
virtual void setComplete() { }
virtual void process() = 0;
};
// ...
int main(int argc, char* argv[])
{
SongJob sj;
Job& jobByRef = sj;
Job* jobByPointer = new SongJob();
// These call the derived implementation of process, on SongJob
jobByRef.process();
jobByPointer->process();
delete jobByPointer;
jobByPointer = new VideoJob();
// This calls the derived implementation of process, on VideoJob
jobByPointer->process();
return 0;
}
And of course, you'll have two different implementations of process. One for each class type.
People will tell you all sorts of "is-a" vs "has-a" stuff, and all sorts of complicated things about this silly "polymorphism" thing; and they're correct.
But this is basically the point of polymorphism, in a utilitarian sense: It is so you don't have to go around checking what type each class it before calling functions on it. You can just call functions on a base type, and the right derived implementation will get called in the end.
BTW, in C++, virtual ... someFunc(...) = 0; means that the type that function is defined in cannot be instantiated, and must be implemented in a derived class. It is called a "pure virtual" function, and the class it is defined on becomes "abstract".
Your problem comes from the fact you're calling a process method on an object. You should have a method Process on the Job class and override this method in your derived classes.
use pure virtual functions:
class Job
{
virtual string getArtist() =0;
};

Polymorphism and checking if an object has a certain member method

I'm developing a GUI library with a friend and we faced the problem of how to determine whether a certain element should be clickable or not (Or movable, or etc.).
We decided to just check if a function exists for a specific object, all gui elements are stored in a vector with pointers to the base class.
So for example if I have
class Base {};
class Derived : public Base
{
void example() {}
}
vector<Base*> objects;
How would I check if a member of objects has a function named example.
If this isn't possible than what would be a different way to implement optional behaviour like clicking and alike.
You could just have a virtual IsClickable() method in your base class:
class Widget {
public:
virtual bool IsClickable(void) { return false; }
};
class ClickableWidget : public Widget
{
public:
virtual bool IsClickable(void) { return true; }
}
class SometimesClickableWidget : public Widget
{
public:
virtual bool IsClickable(void);
// More complex logic punted to .cc file.
}
vector<Base*> objects;
This way, objects default to not being clickable. A clickable object either overrides IsClickable() or subclasses ClickableWidget instead of Widget. No fancy metaprogramming needed.
EDIT: To determine if something is clickable:
if(object->IsClickable()) {
// Hey, it's clickable!
}
The best way to do this is to use mixin multiple inheritance, a.k.a. interfaces.
class HasExample // note no superclass here!
{
virtual void example() = 0;
};
class Derived : public Base, public HasExample
{
void example()
{
printf("example!\n");
}
}
vector<Base*> objects;
objects.push_back(new Derived());
Base* p = objects[0];
HasExample* he = dynamic_cast<HasExample*>(p);
if (he)
he->example();
dynamic_class<>() does a test at runtime whether a given object implements HasExample, and returns either a HasExample* or NULL. However, if you find yourself using HasExample* it's usually a sign you need to rethink your design.
Beware! When using multiple inheritance like this, then (HasExample*)ptr != ptr. Casting a pointer to one of its parents might cause the value of the pointer to change. This is perfectly normal, and inside the method this will be what you expect, but it can cause problems if you're not aware of it.
Edit: Added example of dynamic_cast<>(), because the syntax is weird.
If you're willing to use RTTI . . .
Instead of checking class names, you should create Clickable, Movable, etc classes. Then you can use a dynamic_cast to see if the various elements implement the interface that you are interested in.
IBM has a brief example program illustrating dynamic_cast here.
I would create an interface, make the method(s) part of the interface, and then implement that Interface on any class that should have the functionality.
That would make the most sense when trying to determine if an Object implements some set of functionality (rather than checking for the method name):
class IMoveable
{
public:
virtual ~IMoveable() {}
virtual void Move() = 0;
};
class Base {};
class Derived : public Base, public IMoveable
{
public:
virtual void Move()
{
// Implementation
}
}
Now you're no longer checking for method names, but casting to the IMoveable type and calling Move().
I'm not sure it is easy or good to do this by reflection. I think a better way would be to have an interface (somethign like GUIElement) that has a isClickable function. Make your elements implement the interface, and then the ones that are clickable will return true in their implementation of the function. All others will of course return false. When you want to know if something's clickable, just call it's isClickable function. This way you can at runtime change elements from being clickable to non-clickable - if that makes sense in your context.