Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overloading a super class's function

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++.

like image 417
chrisaycock Avatar asked Jan 04 '11 18:01

chrisaycock


People also ask

Can you overload a superclass method?

Note: In a subclass, you can overload the methods inherited from the superclass. Such overloaded methods neither hide nor override the superclass instance methods—they are new methods, unique to the subclass.

Which functions are overloaded?

C++ lets you specify more than one function of the same name in the same scope. These functions are called overloaded functions, or overloads. Overloaded functions enable you to supply different semantics for a function, depending on the types and number of its arguments.

What is function overloading with an example?

Function overloading is a feature of object-oriented programming where two or more functions can have the same name but different parameters. When a function name is overloaded with different jobs it is called Function Overloading.

Can we overload a member function?

Operator overloading of member function When overloading an operator using a member function: The overloaded operator must be added as a member function of the left operand. The left operand becomes the implicit *this object. All other operands become function parameters.


1 Answers

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.

like image 89
James McNellis Avatar answered Nov 02 '22 23:11

James McNellis