This is a mirror of official site: http://jasper-net.blogspot.com/

Heritage Shared

| Sunday, January 30, 2011
A few days ago, we posted two C++ quizzes based on a question posted in a forum. Let’s review the first question

#include <iostream>
 
class Foo {
public:
   virtual void DoStuff()=0;
};
 
class Bar : public Foo {
public:
   virtual void DoStuff(int a)=0;
};
 
class Baz : public Bar {
public:
   void DoStuff(int a) override
   {
       std::cout << "Baz::DoStuff(int)";
   }
 
   void DoStuff() override
   {
       std::cout << "Baz::DoStuff()";
   }
};
 
int main() {
   Baz baz;
   Bar *pBar = &baz;
 
   pBar->DoStuff();
}


The guy was frustrated because he expected two things:

The code would compile without errors.
Line 30 would end up by calling Baz::DoStuff() which in turn would have printed that same in the output console.
Instead, he got the following compile-time error at that same line

e:\foo.cpp(30): error C2660: 'Bar::DoStuff' : function does not take 0 arguments

The root of this compilation error is at line 11: as we are closing the definition of class Bar without saying anything about method DoStuff without arguments but, instead, having overloaded DoStuff in line 10 with a version that takes an argument of type int, what we just did was hide the original Foo::Stuff() declaration. With that said, the compilation error makes sense.

Read more: Visual C++ Team Blog

Posted via email from Jasper-net

0 comments: