C++: const virtual and virtual

This just bit me in the ass. I thought flagging a method in a class with the ‘const’ keyword was just that: a flag. It’s not. It’s an entirely new function. For example, these two methods have different signatures:

class thing {
virtual foo();
virtual foo() const;

If you have a child class that overrides the parent, you will NOT get a friendly compiler warning if the const’s don’t line up. Boy, did this introduce interesting bugs into my code…

class mything {
virtual foo() const;

class myotherthing : public mything {

The parent was getting called instead of the child. Took me half an hour to figure out what was going on. Pesty const! I’ll never use you again! I thought you were my friend…

So…. If you have two functions foo(), and one’s const and the other is not, which one gets used when you make a call to foo()? Ahhhh?!??!

UPDATE: Hey I figured it out, this is actually in Effective C++ by Scott Meyers. When you are working with an object that is const, such as one that you got via a pass-by-const-reference, then the const version of the method will be invoked. Otherwise, the non-const version will be invoked. Assuming they both exist. If neither exist then whichever one does exist is the one that will be used.

Leave a Reply