Hello dimitar425 !
First, the structure of the class you posted is a singleton and i would strongly suggest avoiding it (google "why are singleton classes avoided in c++").
Second, don't use the
inline
keyword, it doesn't make the function inline it only recommends the compiler that it should be marked inline and the compiler decides if its appropriate, in short leave the compiler the work of figuring out what functions to inline as it will do so on its own for performance.
Third, consider dividing definition and implementation into .cpp and .h files
Now to your question:
Will using it become bad in certain situations or slow down the program? |
your particular code wont slow down the program however if you intend on using runtime polymorphism know that you pay a penalty in performance in terms of vtables:
you call a function of a polymorphic base class -> than the vtable is searched for the correct function pointer to call -> only than is the correct function called.
Will using it become bad ? Only if you miss use it, or abuse it where it can be avoided.
Is the code example down a good way to do it or not?
|
Your example doesn't show polymorphism so il give a short example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
|
#include <iostream>
class Base
{
public:
virtual void call()
{
std::cout << "do base\n";
}
};
class Derived : public Base
{
public:
virtual void call() override
{
std::cout << "do derived\n";
}
};
int main()
{
//non dynamic way
Derived d_a;
Base& b_a = d_a;
b_a.call();
//dynamic way
Base* b = new Derived();
b->call();
delete b;
}
|
A few warnings:
1)beware of slicing (read about it)
2)i used new and delete for a simple example however you should use unique_ptr for dynamic memmory
3)these is not the only way to use polymorphism (look up pure virtual functions and classes, and abstract classes)
lastly here is a source for design patterns :
https://sourcemaking.com/design_patterns
it will provide you with examples that will help you design next projects.
EDIT:
After taking a second look at your class i have one question does CEngine inherit from MyClass ? if so still note that because there is no virtual methods in MyClass you will only be able to call calculate function unless you dynamic_cast the pointer to CEngine and call methods that way. if CEngine does not inherit from MyClass it will not compile. Besides from that its still not polymorphism.