Hello all together,
I'm wondering if you are able to define or instantiate a function for example in the constructor of a class.
Let's say you have this simple class:
class cTest {
public:
cTest( bool bla );
~cTest() {}
void someFunc() {}
};
cTest::cTest( bool bla ) {
if( bla ) {
someFunc = functionBody1;
// or
someFunc {
functionBody1
};
// or something different
} else
someFunc = functionBody2;
}
if someFunc is an often called function, you could avoid testing whether "bla" was true or not every time the function gets called.
I thought about it and two possible solutions came to my mind:
1) Using inheritance:
#include <iostream>
class iTest {
public:
virtual void someFunc() = 0;
};
class cTest1 : public iTest {
public:
void someFunc() { std::cout << "functionBody1\n"; }
};
class cTest2 : public iTest {
public:
void someFunc() { std::cout << "functionBody2\n"; }
};
2) Using function pointers:
#include <iostream>
class cTest {
public:
cTest( bool bla );
~cTest() {}
void someFunc();
private:
void ( cTest::*m_functionPointer )();
void function1() { std::cout << "functionBody1\n"; }
void function2() { std::cout << "functionBody2\n"; }
};
cTest::cTest( bool bla ) {
if( bla )
m_functionPointer = &cTest::function1;
else
m_functionPointer = &cTest::function2;
};
void cTest::someFunc() {
( *this.*m_functionPointer )( );
};
In the program where I need this I cannot use inheritance and don't want to use function pointers. So my question is, is there another (elegant) way to do this, e.g. defining the function in the constructor of the class?
Thanks a lot for your answers!