Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing behavior of an object at runtime

Tags:

c++

How can be changed the behavior of an object at runtime? (using C++)

I will give a simple example. I have a class Operator that contains a method operate. Let’s suppose it looks like this:

double operate(double a, double b){
  return 0.0;
}

The user will give some input values for a and b, and will choose what operation to perform let’s say that he can choose to compute addition or multiplication. Given it’s input all I am allowed to do is instantiate Operator and call operate(a, b), which is written exactly how I mentioned before.

The methods that compute multiplication or addition will be implemented somewhere (no idea where).

In conclusion I have to change the behavior of my Operator object depending on the user's input.

like image 731
Jeni Avatar asked Nov 29 '22 12:11

Jeni


2 Answers

I'm mentioning this only as trivia and can't unrecommend it more, but here we go...

WARNING DANGER!!!

A stupid trick I've seen is called clutching, I think, but it's only for the truely foolish. Basically you swap the virtualtable pointer to that of another class, it works, but it could theoretically destroy the world or cause some other undefined behavior :)

Anyways instead of this just use dynamic classing and kosher C++, but as an experiment the above is kind of fun...

like image 40
Robert Gould Avatar answered Dec 10 '22 16:12

Robert Gould


The standard pattern for this is to make the outer class have a pointer to an "implementation" class.

// derive multiple implementations from this:
class Implementation
{
    virtual ~Implementation() {} // probably essential!

    virtual void foo() = 0;
};

class Switcheroo
{
    Implementation *impl_;

public:
    // constructor, destructor, copy constructor, assignment 
    // must all be properly defined (any that you can't define, 
    // make private)

    void foo()
    {
        impl_->foo();
    }
};

By forwarding all the member functions of Switcheroo to the impl_ member, you get the ability to switch in a different implementation whenever you need to.

There are various names for this pattern: Pimpl (short for "private implementation"), Smart Reference (as opposed to Smart Pointer, due to the fowarding member functions), and it has something in common with the Proxy and Bridge patterns.

like image 93
Daniel Earwicker Avatar answered Dec 10 '22 15:12

Daniel Earwicker