dimanche 27 décembre 2015

virtual function overridden and private, public specifier

I got surprised that a public(or private) virtual function can be overridden by a private(or public) virtual function. See below,

class C{
    public:
    virtual void f(){cout<<"C"<<endl;}
    void g(){f();}

};
class D:public C{
  private:
  virtual void f(){cout<<"D"<<endl;}
};

int main(){
  C * c = new D;
  c->g();
  return 0;
}

the code outputs D. I thought virtual function can only be overridden in the derived class with the same access specifier as in the base class, but this is apparently not how the above code works, am I observing something wrong?

Aucun commentaire:

Enregistrer un commentaire