Overloading a super class's function
Asked Answered
K

2

10

Is there something in the C++ standard that prevents me from overloading a super class's function?

Starting with this pair of classes:

class A {            // super class
    int x;

public:
    void foo (int y) {x = y;}  // original definition
};

class B : public A { // derived class
    int x2;

public:
    void foo (int y, int z) {x2 = y + z;}  // overloaded
};

I can call B::foo() easily:

    B b;
    b.foo (1, 2);  // [1]

But if I try to call A::foo() ...

    B b;
    b.foo (12);    // [2]

... I get a compiler error:

test.cpp: In function 'void bar()':
test.cpp:18: error: no matching function for call to 'B::foo(int)'
test.cpp:12: note: candidates are: void B::foo(int, int)

Just to make sure I wasn't missing something, I changed the name of B's function so that there is no overload:

class B : public A {
    int x2;

public:
    void stuff (int y, int z) {x2 = y + z;}  // unique name
};

And now I can call A::foo() using the second example.

Is this standard? I'm using g++.

Kimbra answered 4/1, 2011 at 18:29 Comment(0)
C
21

You need to use a using declaration inside the definition of class B:

class B : public A {
public:
    using A::foo;          // allow A::foo to be found
    void foo(int, int);
    // etc.
};

Without the using declaration, the compiler finds B::foo during name lookup and effectively does not search base classes for other entities with the same name, so A::foo is not found.

Commiserate answered 4/1, 2011 at 18:31 Comment(2)
to "un-hide" the original member function.Germany
+1 -- note that this is covered (in greater detail) in Scott Meyers' Effective C++ Item 33: Avoid hiding inherited names.Sidras
P
0

You're not overriding A::foo(int)'s implementation, instead you're aliasing A::foo and changing its signature to (int,int) instead of (int). As James McNellis mentioned the using A::foo; declaration makes the function from A available.

Psycho answered 4/1, 2011 at 18:46 Comment(2)
The OP didn't say "overriding", he said overloading, and overloading is what he's doing. Overriding applies to virtual functions.Acetanilide
What he was doing was trying to do was overloading. What he did instead was something akin to overriding, but with the added bonus of aliasing the original method. As noted by James McNellis the using statement addresses the issue, allowing for overloading.Psycho

© 2022 - 2024 — McMap. All rights reserved.