Add method to an existing c++ class

Asked

Viewed 69 times

2

I wonder if in c++ you can increment an existing class by inserting new methods, without touching the class source code directly.

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

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

So within my code, I would like to increment this class inserted a third method:

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

How would that be possible?

  • You can’t extend the class without modifying the class itself. However, there are a number of strategies and best practices that can and should be used in such cases as this, such as the Open/Close principle. A popular strategy is to use functions that accept the class as a parameter (see Factory, Strategy, or Command-type software design standards) or to design the class with its extension in mind (Visitor-type software design standard).

1 answer

1


It is not possible to do this without changing the class code, you need to put at least the function name in the class. You could solve your example like this:

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 content from the original class:

class copia : public original{
public:

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

};
  • Thanks! I just didn’t understand the part of original::void metodo3(), at least here gave compilation error expected unqualified-id before 'void'.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.