ahmed bouchaala
ahmed bouchaala

Reputation: 65

overriding one of 2 overloaded heritated methods c++

This is the problem

I have to maintain and improve a code of this style

class Base {

    virtual char *getname() {return NULL}

    virtual char *getname(int i);

}

class Child1 : public base {

    virtual char *getname() { //its own treatment */

    virtual char *getname(int i) { / its treatment */

}

class Child2 : public base {

    virtual char *getname() { //its own treatment */

    virtual char *getname(int i) { / its treatment */

}

The code like this works.

I found a way to have a generic getname(int i) that works for all children, so I did that

class Base {

    virtual char *getname() {return NULL}

    virtual char *getname(int i) {the new generic code};

}

class Child1 : public base {

    virtual char *getname() { //its own treatment */

    /*virtual char *getname(int i) {*/

}

class Child2 : public base {

    virtual char *getname() { //its own treatment */

    /*virtual char *getname(int i) */

}

The problem I had is the methods hiding.

The overriding of getname() hides the getname(int i) of the base class.

In the base class we have to maintain the 2 methods with these names for compatibility.

The solution of using base::getname, I think we can't use it here, because it can be used when we have only one version of getname in base class, but here we have two.

Have you an idea how to add my generic code which works for all getname(int i) without breaking the actual comportment?

Upvotes: 2

Views: 67

Answers (1)

Peter
Peter

Reputation: 36627

This problem is a manifestation of the hiding rule. By declaring one of the getname() functions in a derived class, all other variants are hidden.

The usual solution is to add using Base::getname() in the definition of each derived class that only overrides one of the inherited forms of getname().

Alternatively, simply give the different variants of the function distinct names.

Upvotes: 1

Related Questions