[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: OT: C++ help



On Wednesday 21 May 2008, Jordi Gutiérrez Hermoso wrote:
> The following code will not compile:
>
>      class foo{};
>
>      class A{
>      public:
>        void f(int a ){a++;};
>      private:
>        virtual void f(foo a) = 0;
>      };
>
>      class B : public A{
>      private:
>        virtual void f(foo a){};
>      };
>
>      int main(){
>        B b;
>        int a=0;
>        b.f(a);
>      }
>
> The problem seems to be that all of my functions being named
> f are somehow colliding with each other. It seems to me that
> the call b.f(a) is unambiguosly pointing to A::f(int), but
> gcc disagrees.

You might as well have written:

class A{
public:
    void f(int a ){a++;};
};

class B : public A{
private:
    virtual void f(foo a){};
};

f in B has the same name as f in A but different args.
This is usually a mistake, so they made it illegal.

If you override one f, you need to override them all.
(or change the name)

To fix:

class B : public A{
public:
    void f(int a){A::f(a);}
private:
    virtual void f(foo a){};
};


Now, try this:

class A{
private:
    virtual void f(foo a)=0;
};

class B : public A {
private:
    virtual void f(foo a){}
};

This doesn't work either, because f in A is private, so B 
doesn't know it exists.  I don't know what it will do.  I think 
you get 2 f's, and still can't make an instance of B because f 
is pure virtual.  Change the private in A to protected, so B 
will see it.

It really is off topic....



Reply to: