Polymorphism and static functions - c++

A followup to this question : C++ : Is there a good way to choose between 2 implementations?
My goal here is that both of these classes can be called at the same runtime. So Polymorphism would be a good and easy way to go with.
I have the following diagram :
But the problem here is that each one of them(a.cpp/h and a_mockup.cpp/h) uses the singelton pattern(contains static functions) and static functions cannot be virtually declared in the baseclass.
Is there a way to solve this problem?

In C++ Virtual functions are invoked during run-time, when you have a pointer/reference to an instance of a class. Static functions aren't bind to a particular instance, they're bind to a class during compile-time. Moreover, C++ doesn't have pointers-to-class functionality. So, there is no such way to solve this.

You must have CRTP as your default design when aiming for static polymorphism.

Related

For what purpose non-virtual method will be used with C++? [duplicate]

This question already has answers here:
Is there any reason not to make a member function virtual?
(7 answers)
Closed 4 years ago.
What will be the purpose of using non-virtual method in terms of functionality with C++? Is there any merit to change a object's method by its object handle rather than its object type? I found many articles about how virtual method will be utilized but I could not find how non-virtual method will be utilized.
Other languages I know of such as Java, Ruby and Python only have virtual method. So functionally non-virtual method is not needed and just be used for performance reason?
OK. I hadn't read the article marked duplicate of. But your answers are still valuable to me in the point the telling the origin of C++ and comparing C++ to other object oriented languages. Thanks everyone to answer.
The answer is very simple : because C++ is not Java.
Programming languages have different philosophies and different ways to accomplish the same result.
Java (and other "OOP-language-where-every-object-is-GCed-and-is-a-reference-type", like C#) encourage you to think about objects in a very specific way: Inheritance and Polymoprphism are the main ways to achieve flexibility and generalization of code. Objects are almost always reference type, meaning that Car car can actually point to Toyota, Ford and whatever. objects are garbaged-collected and dynamically allocated. All objects anyway inherit from an Object class, so inheritance and dynamic polymorphism is anyway imbued into the language objects by the very language design.
C++ is different. the concept of object might be central to the language, but an object is basically a unit of data and functionality. it's a leaner form of a "real" OOP-language object and it usually allocated on the stack, uses RAII to handle its own resources, and is a value type.
Inheritance and Polymorphism exist, but they are inferior to composition and compile-time-polymorphism (templates).
C++ doesn't encourage you to think about objects as a reference type. objects might be a reference type, they might have virtual functions, but this is only one way to achieve flexibility and generalization in C++, as opposed to Java. you might use templates instead, function pointers and opaque types (a-la C style polymorphism), inheritance + overriding function (a-la Java style), Hence, C++ doesn't force you to take the Java route to flexibility - it gives you the opportunity to choose the best way to accomplish things.
When marking a method as virtual, every time such method will be called, the program will have to check the virtual table inside the object that you're calling the method on, it's called dynamic dispatch. It creates quit a bit of overhead compared to normal methods that are resolved using static dispatch.
As big part of C++ is giving the programmer the choice what he wants to do, you can choose if you want static of dynamic linking.
C++ method lookup mechanisms won't allow for polymorphism if it's non-virtual. Defining classes as non-virtual will prevent the overhead and confusion.
Have a look at This question and answers
If a method is not virtual, the compiler knows the address in memory where this method's code will be located right at compile time, and can use it right away. If a method is virtual, it will have to be determined at runtime, which implementation should be called, based on the object type. It adds overhead on every call. So, by making a method non-virtual, you make it more efficient.
It should be mentioned that in some languages it's the other way around: the methods are "virtual" by default, but you can explicitly mark them as "non-virtual" (usually called final).
Non-virtual methods can add additional functionalities specific only to the derived class.
class animal {
public:
virtual string name() = 0;
};
class rhino :public animal {
public:
string name() override { return "Rhino"; }
int getHornSize() { return 10; } // non-virtual method add functionality only specific to rhino class
};

what are the different ways to achieve polymorphism in c++

I know there are a few different ways to achieve polymorphism in c++.
I know of 3 ways to do this:
by using inheritance (through the use of a pointer to a base class)
by using virtual function
by using abstract classes
During a technical discussion on the topic I was told I am missing something and was left hanging...hence I asked the question here.
Is there another way in c++ to to this or is something I said wrong?
Your three ways are really just one: whether the base class is
abstract is an implementation detail; you need virtual
functions, which can be overridden in a derived class.
Other than that: both function overloading and templates provide
a form of polymorphism as well, although it is resolved at
compile time, and not run time. For that matter, you can define
a class in a header file, and provide several different
implementations for it, depending on compile time switches;
that's also a form of polymorphism. (This is often done for
system dependent code. The polymorphism is resolved as
a function of the system you're compiling for.)
I think your discussion was related to different types of polymorphism.
Compile time polymorphism - Ex: Function Overloading, Operator Overloading.
Run time polymorphism - Ex: Inheritance + virtual functions + base class pointer.

Static variables inside instance methods - How to fix that?

Recently I inherited 10 year old code base with some interesting patterns. Among them is static variables inside instance methods. Only single instance of the class is instantiated and I can hardly find reason to justify existence of those static variables in instance methods.
Have you ever designed instance methods with static variables? And what are your rationales?
If this pattern is considered bad then how to fix it?
Note: This question is not relevant to Static variables in instance methods
EDIT:
Some reading:
static class and singleton
http://objectmentor.com/resources/articles/SingletonAndMonostate.pdf
http://www.semantics.org/once_weakly/w01_expanding_monostate.pdf
This is a classic C++ implementation of the singleton pattern, described in one of Scott Meyers C++ books.
Singleton is a controversial pattern, so there is no industry-wide consensus on singleton being good or bad.
An alternative to singletons is a purely static objects. This question has a good discussion.
About the only time I've used static fields in an instanciable class has been as constants.
Generally speaking, you would want to create your class to be either entirely static, or entirely instanciable (with perhaps the exception of constants which you may want to keep static). With a singleton class they will behave in much the same way. The danger of mixing the two techniques is if you decide to make the class no longer a singleton, you might run into some strange behaviours in your now multi-instanced class.
Having a static variable is useful in a procedural function as it can serve as a kind of global variable with limited scope.
The only reason I can see to do something like this in a method would be to have the variable persist over many calls without having to declare a member variable that serves no other purpose. Honestly, I feel like this is just lazy programming and should be avoided.

Root base class in 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.

Is using too much static bad or good?

I like to use static functions in C++ as a way to categorize them, like C# does.
Console::WriteLine("hello")
Is this good or bad? If the functions are used often I guess it doesn't matter, but if not do they put pressure on memory?
What about static const?
but is it good or bad
The first adjective that comes to mind is "unnecessary". C++ has free functions and namespaces, so why would you need to make them static functions in a class?
The use of static methods in uninstantiable classes in C# and Java is a workaround because those languages don't have free functions (that is, functions that reside directly in the namespace, rather than as part of a class). C++ doesn't have that flaw. Just use a namespace.
I'm all for using static functions. These just make sense especially when organized into modules (static class in C#).
However, the moment those functions need some kind of external (non compile-time const) data, then that function should be made an instance method and encapsulated along with its data into a class.
In a nutshell: static functions ok, static data bad.
Those who say static functions can be replaced by namespaces are wrong, here is a simple example:
class X
{
public:
static void f1 ()
{
...
f2 ();
}
private:
static void f2 () {}
};
As you can see, public static function f1 calls another static, but private function f2.
This is not just a collection of functions, but a smart collection with its own encapsulated methods. Namespaces would not give us this functionality.
Many people use the "singleton" pattern, just because it is a common practice, but in many cases you need a class with several static methods and just one static data member. In this case there is no need for a singleton at all. Also calling the method instance() is slower than just accessing the static functions/members directly.
Use namespaces to make a collection of functions:
namespace Console {
void WriteLine(...) // ...
}
As for memory, functions use the same amount outside a function, as a static member function or in a namespace. That is: no memory other that the code itself.
One specific reason static data is bad, is that C++ makes no guarantees about initialization order of static objects in different translation units. In practice this can cause problems when one object depends on another in a different translation unit. Scott Meyers discusses this in Item 26 of his book More Effective C++.
Agree with Frank here, there's not a problem with static (global) functions (of course providing they are organised).. The problems only start to really creep in when people think "oh I will just make the scope on this bit of data a little wider".. Slippery slope :)
To put it really into perspective.. Functional Programming ;)
The problem with static functions is that they can lead to a design that breaks encapsulation. For example, if you find yourself writing something like:
public class TotalManager
{
public double getTotal(Hamburger burger)
{
return burger.getPrice() + burget.getTax();
}
}
...then you might need to rethink your design. Static functions often require you to use setters and getters which clutter a Class's API and makes things more complicated in general. In my example, it might be better to remove Hamburger's getters and just move the getTotal() class into Hamburger itself.
I tend to make classes that consist of static functions, but some say the "right way" to do this is usually to use namespaces instead. (I developed my habits before C++ had namespaces.)
BTW, if you have a class that consists only of static data and functions, you should declare the constructor to be private, so nobody tries to instantiate it. (This is one of the reasons some argue to use namespaces rather than classes.)
For organization, use namespaces as already stated.
For global data I like to use the singleton pattern because it helps with the problem of the unknown initialization order of static objects. In other words, if you use the object as a singleton it is guaranteed to be initialized when its used.
Also be sure that your static functions are stateless so that they are thread safe.
I usually only use statics in conjunction with the friend system.
For example, I have a class which uses a lot of (inlined) internal helper functions to calculate stuff, including operations on private data.
This, of course, increases the number of functions the class interface has.
To get rid of that, I declare a helper class in the original classes .cpp file (and thus unseen to the outside world), make it a friend of the original class, and then move the old helper functions into static (inline) member functions of the helper class, passing the old class per reference in addition to the old parameters.
This keeps the interface slim and doesn't require a big listing of free friend functions.
Inlining also works nicely, so I'm not completely against static.
(I avoid it as much as I can, but using it like this, I like to do.)