Add method to an existing c ++ class

2

I would like to know if in c ++ you can increment an existing class by inserting new methods, without directly manipulating the source code of the class.

For example, if the class below is part of an external library that should not be changed, it contains 2 methods:

class original
{
public:
    void metodo1() {
        std::cout << "método 1" << endl;
    }
    void metodo2() {
        std::cout << "método 2" << endl;
    }
};

Then inside my code, I would like to increment this class by inserting a third method:

void metodo3() {
    std::cout << "método 3" << endl;
}

How would that be possible?

    
asked by anonymous 20.05.2018 / 01:07

1 answer

1

You can not do this without changing the class code, you need to put at least the function name in the class. You could solve your example as follows:

class original
{
public:
    void metodo1() {
        std::cout << "método 1" << endl;
    }
    void metodo2() {
        std::cout << "método 2" << endl;
    }
    void metodo3();
};

Method 3:

void original::metodo3(){
    std::cout << "método 3" << endl;
}

Or you can create a new class and inherit all the contents of the original class:

class copia : public original{
public:

void metodo3(){
    std::cout << "método 3" << endl;
}

};
    
20.05.2018 / 01:50