Overloading a virtual function doesn't work

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>

class Parent
{
        public:
                void func1() {std::cout << "Parent::func1()"<<std::endl;}
                virtual void func1(int bla) =0;
};

class Child:public Parent
{
        public:
                virtual void func1(int bla) {std::cout << "Child::func1("<<bla<<")"<<std::endl;}
};

int main()
{
        Child obj;
        obj.func1();
}


When I try to compile this code, I get the error message:
main.cpp: In function ‘int main()’:
main.cpp:19: error: no matching function for call to ‘Child::func1()’
main.cpp:13: note: candidates are: virtual void Child::func1(int)


I want Parent::func1() being inherited to Child. Calling Child::func1() should call Parent::func1(). Why doesn't this work when func1() is overloaded with a virtual function?
I guess it gives problems with name lookup.
Try adding using Parent::func1; to Child
That works - thank you :)
Nevertheless it seems strange to me that the compiler doesn't recognize that by itself.
The C++ ISO standard has many pages on derived member lookup, it may be a much more complex topic than it looks
closed account (1yR4jE8b)
am I the only one that noticed that his function signature was

void func1(int bla)

and the code he was trying to compile was using
obj.func1();

The compiler was telling him it needed a parameter, and not that it was having a problem doing function lookup.
closed account (1yR4jE8b)
am I the only one that noticed that his function signature was

void func1(int bla)

and the code he was trying to compile was using
obj.func1();

The compiler was telling him it needed a parameter, and not that it was having a problem doing function lookup.
I want Parent::func1() being inherited to Child. Calling Child::func1() should call Parent::func1(). Why doesn't this work when func1() is overloaded with a virtual function?

It doesn't work because of name hiding. When a derived class has a member function with the same name as a member function of the base class (even if it has a different signature), the derived class member hides the one that it inherits from the parent. (The same applies to data members.)

Another solution is to specify the scope in the function call:

1
2
3
4
5
int main()
{
    Child obj;
    obj.Parent::func1();
}
am I the only one that noticed that his function signature was

void func1(int bla)

and the code he was trying to compile was using
obj.func1();

The compiler was telling him it needed a parameter, and not that it was having a problem doing function lookup.

True, but the compiler didn't understand what he was trying to do. As he said, he wanted to call the func1() that was inherited from the parent, not the virtual func1(int).
Topic archived. No new replies allowed.