Re: why does this not compile ?

From: E. Robert Tisdale (E.Robert.Tisdale_at_jpl.nasa.gov)
Date: 03/24/05


Date: Wed, 23 Mar 2005 20:02:49 -0800

Artie Gold wrote:

> wim delvaux wrote:
>
>> class A {
>> public :
>> virtual void a(int x) = 0;
>> virtual void a(void) {
>> printf("a without\n");
>> }
>> };
>>
>> class B: public A {
>> public :
>> virtual void a(int x) {
>> printf( "a with\n" );
>> }
>> };
>>
>> int main(void) {
>> B SomeB;
>>
>> SomeB.a();
>> SomeB.a(1);
>> }
>>
>> The error I get with gcc 3.4 is
>>
>> t.cpp: In function `int main()':
>> t.cpp:25: error: no matching function for call to `B::a()'
>> t.cpp:17: error: candidates are: virtual void B::a(int)
>>
>> What is going on ? Why can't I define two 'a' with different arguments ?
>
> The overloading is fine. The problem you're seeing is due to the fact
> that C++ only does dynamic dispatch on a pointer to object or a
> reference to object, not on an object itself.

Then why does this work?

> cat t.cpp
         #include <iostream>

         class A {
         public:
           virtual void a(int x) = 0;
           void z(void) {
             std::cout << "a without" << std::endl;
             }
           };

         class B: public A {
         public:
           virtual void a(int x) {
             std::cout << "a with" << std::endl;
             }
           };

         int main(int argc, char* argv[]) {
           B someB;

           someB.z();
           someB.a(1);
           return 0;
           }

> g++ -Wall -ansi -pedantic -o t t.cpp
> ./t
         a without
         a with



Relevant Pages