Giving a function implementation more than one name in c++ - c++

Let say I have a basic 2D vector class something like
class vector2
{
int x, y;
}
these two values could be used to represent a position as well as a width and height. does C++ provide a away for me to impliment a function such as vector2::getXpos() and then also define vector2::getWidth() and have it use the same implementation.
I know that I could just make both of these function inline, but the compiler might decide to not inline these functions. so if getWidth just called getXpos you would end up with two function calls.
A more relistic example of what I would want to use this for is getLength() and erm... getSpan() (thinking of like a screen here for when you say 40" tv)
I would assume that this would be a simple case of something like a special function definition... I did find this page but this sounds like it is a C feature... and a bit of a hack to get working.
EDIT
I am not asking about the mechanics of inline functions... I basicaly want to do something functionally like
class MyClass
{
void ActaullyDoStuff();
public:
void foo(){ActaullyDoStuff();}
void bar(){ActuallyDoStuff();}
}
but where I can just write something like
class MyBetterClass
{
public:
void foo(){ /* BLOCK OF CODE */ }
void bar(){ /* DO WHAT EVER foo() DOES */ }
}
I want bar() to be another way of just doing foo() so that the same functional code can have different, more appropriate names depending on the situation.

but the compiler might decide to not
inline these functions
Then the compiler probably has a good reason to do so.
I think this is a non problem, just have the function with the alternative name call the "real" function, and the compiler will most likely inline it.
EDIT:
If that didn't convince you, it is possible to use __forceinline in visual studio.
Here is the way to force inline in GCC.
EDIT2:
class MyBetterClass
{
public:
void foo(){ /* BLOCK OF CODE */ }
__forceinline void bar(){ foo(); /* DO WHAT EVER foo() DOES */ }
}

Using C++11 you could do:
//works for non-template non-overloaded functions:
const auto& new_fn_name = old_fn_name;
Other solutions:
How do I assign an alias to a function name in C++?

It appears you're not thinking about this in an object oriented way. I have to second mjfgates advice that you really don't want to do this.
What you want to do is abstract the idea of a vector into a class and implement the common methods you might want to use with a vector. In fact, you may want to consider implementing your class example above as a "Point" class and then have a "Vector" class aggregate two point classes.
Using your example, your class would not be well defined if it was used for two different purposes. Let's say you want to make a method on some class to draw vector2. You would have to know which instances of vector2 are representing a starting point and which ones are representing a width/height. You'd probably also need a third representation to represent direction. The easier way is to implement the vector in terms of getStartPoint, getEndPoint, and any other methods that will do calculations appropriate for the vector. Then the consumer doesn't need to know about the internal working of the vector2 class, they just call the methods to get the information they need.

Your referenced link is AFAIK not a C feature either, but something specific to that particular compiler.
C++ provides such a mechanism: it happens to be inlined functions! Worrying about the compiler not optimizing away the redundant call in an inlineable function is definitely premature optimization. Inline, then measure if you're worried about performance.
If you're absolutely insisting on eliminating the merest chance of a redundant call, you might do something with preprocessor #defines... but beware: macros do not respect class boundaries, and your header files will sooner or later stomp on some other, unrelated code. Better not go there.

you could use preprocessor #defines.... if you're into the world's worst bugs. You'll get the equivalent of guaranteed inline if you want, or just aliases if you want that too.

So, you want to have two functions, on the same object, that return exactly the same data, as the same data type.
Don't DO that.
Providing more than one path to the same data is one of those things that sounds like it might be convenient for whoever's going to be using your object-- until you think about it. What happens is that six months down the road, somebody turns up a bug in one of the two functions, and you fix that function but not the other one, so the bug's still there. Or the programmer who's writing clients for your object is driven half-insane wondering what the difference is between getLength() and getSpan().
The one time I'd do this would be when implementing an interface that requires a duplicate of an existing member function. In that case, the interface's function is going to be virtual, so the notion of inlining goes out the window.

Related

Using smaller functions to break up long methods - correct style / how to declare

I have a long and confusing static method in one of my classes. It is full or error checking code and as a consequence is turning into unreadable spaghetti! It looks something like this:
void myMethod(int foo, int bar)
{
int y = functionCall(foo);
if (!y)
{
int x = functionCall(bar);
if (!x)
{
// lots of code with further nested ifs for error checking
// it all starts to get a bit confusing
}
else
{
// error handling
}
}
else
{
// error handling
}
}
So that the code is readable and more modular (allowing me to more easily test/ maintain etc) I would like to break it down into some smaller functions. This is not about code reuse as the functions will only ever be called from this one place - it is purely about readability and making 100's of lines of complicated code more understandable for humans.
So my question is this.
If I am to do this will I lose efficiency as I am making unnecessary calls and so extra work for the processor?
If I make these smaller functions should I declare them inline to help the linker realise that they are only used by this one function and should be blown up in place?
Will the linker be able to manage this kind of optimization itself?
Finally if I am to declare it inline what is the correct way to do this?
Should I put the inline function declaration in the header file and the code body in the .cpp file?
i.e.
in MyClass.hpp :
inline static int myMethodPart1();
in MyClass.cpp
int MyClass::myMethodPart1()
{ /* body */ }
Or should I perhaps not declare it in the header or ..... ?
With regards to how to organize and divide the code, I would say you need to use good judgment. If you feel it is a problem big enough to post here, then addressing it is probably worth the effort. That said, I will try to address the components of your post individually.
The cost of function calls. Function calls are insanely cheap. The system essentially just dereferences a single pointer and it’s there. Similar already happens in loops, conditionals, and other forms of branching. Declaring:
While( x != 0 )
{
Do stuff;
}
Will compile, at a low level, to effectively having “do stuff;” as a separate function called repeatedly. As such, the cost of splitting your function into multiple functions is low and possibly, if done cleanly and with a smart compiler, non-existent.
Regarding inlining. As I explained in the comments, the inline keyword does not mean (quite) what you think it means and what it suggests it means. Compilers have a tendency to ignore inline with regards to actually inlining the function, and at best take it as a suggestion. What inline does do is prevent multiple definitions of the function from becoming an error. This is important behavior if you define a function within a header, because that function definition will be compiled into every cpp's object file. If not declared inline, linking these objects into an executable can generate a multiple definition error. Some compilers implicitly inline functions defined in such a way, but you should never depend upon compiler-specific behavior.
Actually getting a function inlined is to an extent up to the good graces of the compiler. I have seen it stated, although I cannot now find where, that defining a function within the class declaration (in the header) is a fairly strong nod to the compiler to inline.
That said, as I noted before, inlining is not a particularly important matter. The cost of calling a function is insanely low, and really the only area one should be concerned about it is in functions called often - like getter and setter functions.
How to use inline. Having established inline doesn't inline, usually, your question about using it is mostly addressed as above. If you define a function within the class declaration, use the inline keyword to avoid possible linker errors. Otherwise, it's largely a meaningless keyword to most modern compilers so far as I am aware.
Where to put functions formed from splitting a single function. This is very much an opinion based question but there are two options I think that seem best:
First, you can make it a protected member of the class. If you do so, you should probably include a symbolic nod that this is not a general-purpose function - a leading underscore in the name is typically the symbol for "do not touch."
Alternatively, you can define the extra functions in the .cpp file, not within the class itself. For example [MyClass.cpp]:
void functionA()
{
stuff;
}
void functionB()
{
stuff;
}
void MyClass::myFunction()
{
functionA();
functionB();
}
This completely prevents these functions form being called outside this cpp file. It also prevents calls from child classes, which may or may not be desirable behavior. Use your discretion in choosing where to put them.
A final note. Be careful about how you divide up complicated functions, or you could end up with something worse than a single function. Moving things elsewhere might only serve to hide the fact the actual logic is messy. I personally find it much simpler to follow a single branching function than one that calls other functions. It is more difficult to read, especially for someone not familiar with the code, if calls are being made outside the function for potentially non-obvious reasons.
It might be beneficial to think how you could reorganize the code to be simpler, if possible, and keep it in one function - or divide it in such a way it would be reusable.

Sharing function between classes

I have three classes which each store their own array of double values. To populate the arrays I use a fairly complex function, lets say foo(), which takes in several parameters and calculates the appropriate values for the array.
Each of my three classes uses the same function with only minor adjustments (i.e. the input parameters vary slightly). Each of the classes is actually quite similar although they each perform separate logic when retrieving the values of the array.
So I am wondering how should I 'share' the function so that all classes can use it, without having to duplicate the code?
I was thinking of creating a base class which contained the function foo() and a virtual get() method. My three classes could then inherit this base class. Alternatively, I was also thinking perhaps a global function was the way to go? maybe putting the function into a namespace?
If the classes have nothing in common besides this foo() function, it is silly to put it in a base class; make it a free function instead. C++ is not Java.
Declaring of a function in base class sounds the most appropriate solution. Not sure if you need virtual "get" though, instead just declare the array in the base class and provide access method(s) for descendants.
More complex part is "the input parameters vary slightly". If parameters differ by type only then you may write a template function. If difference is more significant than the only solution I see is splitting main function into several logic blocks and using these blocks in descendant classes to perform final result.
If your classes are quite similar, you could create a template class with three different implementations that has the function foo<T>()
Implement that function in base class. If these classes are similar as you say, they should be derived from one base class anyway! If there are several functions like foo(), it might be reasonable in some cases to combine them into another class which is utilized by/with your classes.
If the underlying data of the class is the same (Array of doubles), considering using a single class and overloading the constructor, or just use 3 different functions:
void PopulateFromString(const string&)
void PopulateFromXml(...)
void PopulateFromInteger(...)
If the data or the behavior is different in each class type, then your solution of base class is good.
You can also define a function in the same namespace as your classes as utility function, if it has nothing to do with specific class behavior (Polymorphism). Bjarne StroupStroup recommends this method by the way.
For the purpose of this answer, I am assuming the classes you have are not common in any other outwards way; they may load the same data, but they are providing different interfaces.
There are two possible situations here, and you haven't told us which one it is. It could be more like
void foo(double* arr, size_t size) {
// Some specific code (that probably just does some preparation)
// Lots of generic code
// ...
// Some more specific code (cleanup?)
}
or something similar to
void foo(double* arr, size_t size) {
// generic_code();
// ...
// specific_code();
// generic_code();
// ...
}
In the first case, the generic code may very well be easy to put into a separate function, and then making a base class doesn't make much sense: you'll probably be inheriting from it privately, and you should prefer composition over private inheritance unless you have a good reason to. You could put the new function in its own class if it benefits from it, but it's not strictly necessary. Whether you put it in a namespace or not depends on how you're organising your code.
The second case is trickier, and in that case I would advise polymorphism. However, you don't seem to need runtime polymorphism for this, and so you could just as well do it compile-time. Using the fact that this is C++, you can use CRTP:
template<typename IMPL>
class MyBase {
void foo(double* arr, size_t size) {
// generic code
// ...
double importantResult = IMPL::DoALittleWork(/* args */);
// more generic code
// ...
}
};
class Derived : MyBase<Derived> {
static double DoALittleWork(/* params */) {
// My specific stuff
return result;
}
};
This gives you the benefit of code organisation and saves you some virtual functions. On the other hand, it does make it slightly less clear what functions need to be implemented (although the error messages are not that bad).
I would only go with the second route if making a new function (possibly within a new class) would clearly be uglier. If you're parsing different formats as Andrey says, then having a parser object (that would be polymorphic) passed in would be even nicer as it would allow you to mock things with less trouble, but you haven't given enough details to say for sure.

To inline or not to inline

I've been writing a few classes lately; and I was wondering whether it's bad practice, bad for performance, breaks encapsulation or whether there's anything else inherently bad with actually defining some of the smaller member functions inside a header (I did try Google!). Here's an example I have of a header I've written with a lot of this:
class Scheduler {
public:
typedef std::list<BSubsystem*> SubsystemList;
// Make sure the pointer to entityManager is zero on init
// so that we can check if one has been attached in Tick()
Scheduler() : entityManager(0) { }
// Attaches a manager to the scheduler - used by Tick()
void AttachEntityManager( EntityManager &em )
{ entityManager = &em; }
// Detaches the entityManager from a scheduler.
void DetachEntityManager()
{ entityManager = 0; }
// Adds a subsystem to the scheduler; executed on Tick()
void AddSubsystem( BSubsystem* s )
{ subsystemList.push_back(s); }
// Removes the subsystem of a type given
void RemoveSubsystem( const SubsystemTypeID& );
// Executes all subsystems
void Tick();
// Destroys subsystems that are in subsystemList
virtual ~Scheduler();
private:
// Holds a list of all subsystems
SubsystemList subsystemList;
// Holds the entity manager (if attached)
EntityManager *entityManager;
};
So, is there anything that's really wrong with inlining functions like this, or is it acceptable?
(Also, I'm not sure if this'd be more suited towards the 'code review' site)
Inlining increases coupling, and increases "noise" in the class
definition, making the class harder to read and understand. As a
general rule, inlining should be considered as an optimization measure,
and only used when the profiler says it's necessary.
There are a few exceptions: I'll always inline the virtual destructor of
an abstract base class if all of the other functions are pure virtual;
it seems silly to have a separate source file just for an empty
destructor, and if all of the other functions are pure virtual, and
there are no data members, the destructor isn't going to change without
something else changing. And I'll occasionally provide inlined
constructors for "structures"—classes in which all data members
are public, and there are no other functions. I'm also less rigorous
about avoiding inline in classes which are defined in a source file,
rather than a header—the coupling issues obviously don't apply in
that case.
All of your member functions are one-liners, so in my opinion thats acceptable. Note that inline functions may actually decrease code size (!!) because optimizing compilers increase the size of (non-inline) functions in order to make them fit into blocks.
In order to make your code more readable I would suggest to use inline definitions as follows:
class Scheduler
{
...
void Scheduler::DetachEntityManager();
...
};
inline void Scheduler::DetachEntityManager()
{
entityManager = 0;
}
In my opinion thats more readable.
I think inlining (if I understood you right, you mean the habit of writing trivial code right into the header file, and not the compiler behaviour) aids readability by two factors:
It distinguishes trivial methods from non-trivial ones.
It makes the effect of trivial methods available at a glance, being self-documenting code.
From a design POV, it doesn't really matter. You are not going to change your inlined method without changing the subsystemList member, and a recompile is necessary in both cases. Inlining does not affect encapsulation, since the method is still a method with a public interface.
So, if the method is a dumb one-liner without a need for lengthy documentation or a conceivable need of change that does not encompass an interface change, I'd advise to go for inlining.
It will increase executable size and in some occasions this will lead to worse performance.
Keep in mind that an inline method requires it's source code to be visible to whoever uses it (ie. code in the header) this means that a small change in the implementation of your inlined methods will cause a recompilation on everything that uses the header where the inline method was defined.
On the other hand, it is a small performance increase, it's good for short methods that are called really frequently, since it will save you the typical overhead of calling to methods.
Inline methods are fine if you know where to use them and don't spam them.
Edit:
Regarding style and encapsulation, using inline methods prevents you from using things like Pointer to implementation, forward declarations, etc.. since your code is in the header.
Inlining has three "drawbacks" at least:
inline functions are at odds with the virtual keyword (I mean conceptually, IMO, either you want a piece of code to be substituted for the function call, or you want the function call to be virtual, i.e. polymorphic; anyway, see also this for more details as to when it could make sense practically);
your binary code will be larger;
if you include the inline method in the class definition, you reveal implementation detail.
Apart from that it is plainly ok to inline methods, although it is also true that modern compilers are already sufficiently smart to inline methods on their own when it makes sense for performance. So, in a sense I think it is better to leave it to the compiler altogether...
Methods inside class body are usually inline automatically. Also, inline is a suggestion and not a command. Compilers are generally smart enough to judge whether to inline a function or not.
You can refer to this similar question.
In fact you can write all your functions in the header file, if the function is too large the compiler will automatically not inline the function. Just write the function body where you think it fits best, let the compiler decide. The inline keyword is ignored often as well, if you really insist on inlining the function use __forceinline or something similar (I think that is MS specific).

Why bother with virtual functions in c++?

This is not a question about how they work and declared, this I think is pretty much clear to me. The question is about why to implement this?
I suppose the practical reason is to simplify bunch of other code to relate and declare their variables of base type, to handle objects and their specific methods from many other subclasses?
Could this be done by templating and typechecking, like I do it in Objective C? If so, what is more efficient? I find it confusing to declare object as one class and instantiate it as another, even if it is its child.
SOrry for stupid questions, but I havent done any real projects in C++ yet and since I am active Objective C developer (it is much smaller language thus relying heavily on SDK's functionalities, like OSX, iOS) I need to have clear view on any parallel ways of both cousins.
Yes, this can be done with templates, but then the caller must know what the actual type of the object is (the concrete class) and this increases coupling.
With virtual functions the caller doesn't need to know the actual class - it operates through a pointer to a base class, so you can compile the client once and the implementor can change the actual implementation as much as it wants and the client doesn't have to know about that as long as the interface is unchanged.
Virtual functions implement polymorphism. I don't know Obj-C, so I cannot compare both, but the motivating use case is that you can use derived objects in place of base objects and the code will work. If you have a compiled and working function foo that operates on a reference to base you need not modify it to have it work with an instance of derived.
You could do that (assuming that you had runtime type information) by obtaining the real type of the argument and then dispatching directly to the appropriate function with a switch of shorts, but that would require either manually modifying the switch for each new type (high maintenance cost) or having reflection (unavailable in C++) to obtain the method pointer. Even then, after obtaining a method pointer you would have to call it, which is as expensive as the virtual call.
As to the cost associated to a virtual call, basically (in all implementations with a virtual method table) a call to a virtual function foo applied on object o: o.foo() is translated to o.vptr[ 3 ](), where 3 is the position of foo in the virtual table, and that is a compile time constant. This basically is a double indirection:
From the object o obtain the pointer to the vtable, index that table to obtain the pointer to the function and then call. The extra cost compared with a direct non-polymorphic call is just the table lookup. (In fact there can be other hidden costs when using multiple inheritance, as the implicit this pointer might have to be shifted), but the cost of the virtual dispatch is very small.
I don't know the first thing about Objective-C, but here's why you want to "declare an object as one class and instantiate it as another": the Liskov Substitution Principle.
Since a PDF is a document, and an OpenOffice.org document is a document, and a Word Document is a document, it's quite natural to write
Document *d;
if (ends_with(filename, ".pdf"))
d = new PdfDocument(filename);
else if (ends_with(filename, ".doc"))
d = new WordDocument(filename);
else
// you get the point
d->print();
Now, for this to work, print would have to be virtual, or be implemented using virtual functions, or be implemented using a crude hack that reinvents the virtual wheel. The program need to know at runtime which of various print methods to apply.
Templating solves a different problem, where you determine at compile time which of the various containers you're going to use (for example) when you want to store a bunch of elements. If you operate on those containers with template functions, then you don't need to rewrite them when you switch containers, or add another container to your program.
A virtual function is important in inheritance. Think of an example where you have a CMonster class and then a CRaidBoss and CBoss class that inherit from CMonster.
Both need to be drawn. A CMonster has a Draw() function, but the way a CRaidBoss and a CBoss are drawn is different. Thus, the implementation is left to them by utilizing the virtual function Draw.
Well, the idea is simply to allow the compiler to perform checks for you.
It's like a lot of features : ways to hide what you don't want to have to do yourself. That's abstraction.
Inheritance, interfaces, etc. allow you to provide an interface to the compiler for the implementation code to match.
If you didn't have the virtual function mecanism, you would have to write :
class A
{
void do_something();
};
class B : public A
{
void do_something(); // this one "hide" the A::do_something(), it replace it.
};
void DoSomething( A* object )
{
// calling object->do_something will ALWAYS call A::do_something()
// that's not what you want if object is B...
// so we have to check manually:
B* b_object = dynamic_cast<B*>( object );
if( b_object != NULL ) // ok it's a b object, call B::do_something();
{
b_object->do_something()
}
else
{
object->do_something(); // that's a A, call A::do_something();
}
}
Here there are several problems :
you have to write this for each function redefined in a class hierarchy.
you have one additional if for each child class.
you have to touch this function again each time you add a definition to the whole hierarcy.
it's visible code, you can get it wrong easily, each time
So, marking functions virtual does this correctly in an implicit way, rerouting automatically, in a dynamic way, the function call to the correct implementation, depending on the final type of the object.
You dont' have to write any logic so you can't get errors in this code and have an additional thing to worry about.
It's the kind of thing you don't want to bother with as it can be done by the compiler/runtime.
The use of templates is also technically known as polymorphism from theorists. Yep, both are valid approach to the problem. The implementation technics employed will explain better or worse performance for them.
For example, Java implements templates, but through template erasure. This means that it is only apparently using templates, under the surface is plain old polymorphism.
C++ has very powerful templates. The use of templates makes code quicker, though each use of a template instantiates it for the given type. This means that, if you use an std::vector for ints, doubles and strings, you'll have three different vector classes: this means that the size of the executable will suffer.

dynamical binding or switch/case?

A scene like this:
I've different of objects do the similar operation as respective func() implements.
There're 2 kinds of solution for func_manager() to call func() according to different objects
Solution 1: Use virtual function character specified in c++. func_manager works differently accroding to different object point pass in.
class Object{
virtual void func() = 0;
}
class Object_A : public Object{
void func() {};
}
class Object_B : public Object{
void func() {};
}
void func_manager(Object* a)
{
a->func();
}
Solution 2: Use plain switch/case. func_manager works differently accroding to different type pass in
typedef enum _type_t
{
TYPE_A,
TYPE_B
}type_t;
void func_by_a()
{
// do as func() in Object_A
}
void func_by_b()
{
// do as func() in Object_A
}
void func_manager(type_t type)
{
switch(type){
case TYPE_A:
func_by_a();
break;
case TYPE_B:
func_by_b();
default:
break;
}
}
My Question are 2:
1. at the view point of DESIGN PATTERN, which one is better?
2. at the view point of RUNTIME EFFCIENCE, which one is better? Especailly as the kinds of Object increases, may be up to 10-15 total, which one's overhead oversteps the other? I don't know how switch/case implements innerly, just a bunch of if/else?
Thanks very much!
from the view point of DESIGN PATTERN, which one is better?
Using polymorphism (Solution 1) is better.
Just one data point: Imagine you have a huge system built around either of the two and then suddenly comes the requirement to add another type. With solution one, you add one derived class, make sure it's instantiated where required, and you're done. With solution 2 you have thousands of switch statements smeared all over the system and it is more or less impossible to guarantee you found all the places where you have to modify them for the new type.
from the view point of RUNTIME EFFCIENCE, which one is better? Especailly as the kinds of Object
That's hard to say.
I remember a footnote in Stanley Lippmann's Inside the C++ Object Model, where he says that studies have shown that virtual functions might have a small advantage against switches over types. I would be hard-pressed, however, to cite chapter and verse, and, IIRC, the advantage didn't seem big enough to make the decision dependent on it.
The first solution is better if only because it's shorter in code. It is also easier to maintain and faster to compile: if you want to add types you need only add new types as headers and compilation units, with no need to change and recompile the code that is responsible for the type mapping. In fact, this code is generated by the compiler and is likely to be as efficient or more efficient than anything you can write on your own.
Virtual functions at the lowest level cost no more than an extra dereference in a table (array). But never mind that, this sort of performance nitpicking really doesn't matter at this microscopic numbers. Your code is simpler, and that's what matters. The runtime dispatch that C++ gives you is there for a reason. Use it.
I would say the first one is better. In solution 2 func_manager will have to know about all types and be updated everytime you add a new type. If you go with solution 1 you can later add a new type and func_manager will just work.
In this simple case I would actually guess that solution 1 will be faster since it can directly look up the function address in the vtable. If you have 15 different types the switch statement will likely not end up as a jump table but basically as you say a huge if/else statement.
From the design point of view the first one is definitely better as thats what inheritance was intended for, to make different objects behave homogeneously.
From the efficiency point of view in both alternatives you have more or less the same generated code, somewhere there must be the choice making code. Difference is that inheritance handles it for you automatically in the 1st one and you do it manually in the 2nd one.
Using "dynamic dispatch" or "virtual dispatch" (i.e. invoking a virtual function) is better both with respect to design (keeping changes in one place, extensibility) and with respect to runtime efficiency (simple dereference vs. a simple dereference where a jump table is used or an if...else ladder which is really slow). As a slight aside, "dynamic binding" doesn't mean what you think... "dynamic binding" refers to resolving a variable's value based on its most recent declaration, as opposed to "static binding" or "lexical binding", which refers to resolving a variable by the current inner-most scope in which it is declared.
Design
If another programmer comes along who doesn't have access to your source code and wants to create an implementation of Object, then that programmer is stuck... the only way to extend functionality is by adding yet another case in a very long switch statement. Whereas with virtual functions, the programmer only needs to inherit from your interface and provide definitions for the virtual methods and, walla, it works. Also, those switch statements end up all over the place, and so adding new implementations almost always requires modifying many switch statements everywhere, while inheritance keeps the changes localized to one class.
Efficiency
Dynamic dispatch simply looks up a function in the object's virtual table and then jumps to that location. It is incredibly fast. If the switch statement uses a jump table, it will be roughly the same speed; however, if there are very few implementations, some programmer is going to be tempted to use an if...else ladder instead of a switch statement, which generally is not able to take advantage of jump tables and is, therefore, slower.
Why nobody suggests function objects? I think kingkai interested in solving the problem, not only that two solutions.
I'm not experienced with them, but they do their job:
struct Helloer{
std::string operator() (void){
return std::string("Hello world!");
}
};
struct Byer{
std::string operator() (void){
return std::string("Good bye world!");
}
};
template< class T >
void say( T speaker){
std::cout << speaker() << std::endl;
}
int main()
{
say( Helloer() );
say( Byer() );
}
Edit: In my opinion this is more "right" approach, than classes with single method (which is not function call operator). Actually, I think this overloading was added to C++ to avoid such classes.
Also, function objects are more convenient to use, even if you dont want templates - just like usual functions.
In the end consider STL - it uses func objects everywhere and looks pretty natural. And I dont even mention Boost