Re: dynamic function definition
"cesco" <fd.calabrese@gmail.com> wrote:
I need to define the body of a function in the constructor of a class.
For example, the class has a member function Log (that is the public
interface of the class), but I want the body of this function to be
defined as something or as something else in the constructor of the
class:
class MyClass
{
public:
void Log(const int& id, const int& value);
private:
void LogON(const int& id, const int& value);
void LogOFF();
};
MyClass::MyClass
{
// define here whether the function "Log" will behave as LogON or
LogOFF according to a switch
}
void MyClass::LogON(const int& id, const int& value)
{
// do something like push_back
}
void MyClass::LogOFF()
{
// do nothing
}
// don't know if I need or not the following definition
void MyClass::Log(const int& id, const int& value)
{
}
Any suggestion on how to do this?
Yes. Use an interpreted language such as APL or Perl.
On-the-fly self-reprogramming programs are impossible in
a compiled language such as C++.
But you really don't need "dynamic function definition" for
what you describe. Polymorphism would work for you, I think.
Something like:
class MyLogBase // Abstract base; can't be instantiated
{
public:
// (contstructors, etc.)
// Pure Virtual Function:
virtual void Log(const int& id, const int& value) = 0;
private:
// etc.
};
class MyLogOn : public MyLogBase
{
public:
// (contstructors, etc.)
// over-ride the pure virtual function from the base:
void Log(const int& id, const int& value)
{
std::cout << "LOG ON" << std::endl;
}
private:
// etc.
};
class MyLogOff : public MyLogBase
{
public:
// (contstructors, etc.)
// over-ride the pure virtual function from the base:
void Log(const int& id, const int& value)
{
std::cout << "LOG OFF" << std::endl;
}
private:
// etc.
};
Research "polymorphism", "pure virtual function", and
"abstract base class" in a good C++ book for more info.
--
Cheers,
Robbie Hatley
East Tustin, CA, USA
lone wolf intj at pac bell dot net
(put "[usenet]" in subject to bypass spam filter)
http://home.pacbell.net/earnur/