[Solved] Delegation in C++


First, let’s use a typedef for the function:

typedef int agechanger(int);

this makes a new type, agechanger, which will be used in code for passing the function instances around.

Now, you should give your person class a proper constructor, and properly incapsulate the age field providing a public getter. Then add a method that accepts a function as argument, function of type agechanger, of course.

class person
{
private:
    int age;
public:
    person(int age){
        this->age = age;
    }

    int getAge() const {
        return age;
    }
    void changeAge(agechanger f)
    {
        age = f(age);
    }
};

Then define a function that fits our type, inside a class:

class addNumber {
public:
    static int changeAge(int arg) {
        return arg + 1;
    }
};

Notice that the function is marked as static and returns the passed int incremented by one.

Let’s test everything in a main:

int main()
{
    person Olaf(100); //instance of person, the old Olaf

    Olaf.changeAge(addNumber::changeAge); //pass the function to the person method

    std::cout << Olaf.getAge() << std::endl; //Olaf should be even older, now
}

Let’s make and use a different function, ouside a class, this time:

int younger(int age)
{
    return age -10;
}

int main(){

    person Olaf(100);

    Olaf.changeAge(younger);

    std::cout << Olaf.getAge() << std::endl; // Olaf is much younger now!
}

I hope that having code that works is going to help you understand things better. The topic you’re asking about, here, is generally considered advanced, while I think you should review some more basic topics of c++, first (functions and classes, for example).

solved Delegation in C++