3

Possible Duplicate:
Overriding a Base's Overloaded Function in C++

I have a class like this one:

class Object {
public:
    int alignment() const;
    virtual void alignment(int i);
};

that I try to subclass like this:

class Sub : public Object {
public:
    virtual void alignment(int i);
};

then:

Sub *sub = new Sub();
sub->alignment(10);
int a = sub->alignment();

The compiler (clang 1.0) generates an error: "Too few arguments to function call, expected 1, have 0." I don't understand why the virtual function that takes an argument is getting confused with the non-virtual const one. Can someone please explain why?

Community
  • 1
  • 1
joshfisher
  • 227
  • 1
  • 3
  • 8

4 Answers4

3

Yes. Doing it like this hides the function overload in the base class. Add the following to your Sub class to fix this:

using Object::alignment;
Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
3

Name lookup doesn't work the way you think it does.

The compiler starts at Sub, and looks to see if it has a function named alignment. It does... so it stops looking. It never even bothers looking at the parent classes, because it already found a match. So the virtual override in Sub hides the non-virtual function in Object. Unfortunately, that match requires an integral parameter, and you did not provide one.

Note that even if both alignment functions in Object were virtual, nothing would change. By overriding one method, you hide all the other versions.

To fix it, provide a using declaration within Sub to bring the other function into scope, such that name lookup will find both versions.

Dennis Zickefoose
  • 10,791
  • 3
  • 29
  • 38
1

In my opinion the following makes the intention clearer:
int a = sub->Object::alignment();

Also you didn't specify the public keyword, as mentioned before by Space_C0wb0y

Tony
  • 9,672
  • 3
  • 47
  • 75
the_source
  • 648
  • 1
  • 6
  • 12
-2

int a = sub->alignment();

You didn't specify a parameter where it's expecting one.

MGZero
  • 5,812
  • 5
  • 29
  • 46