about virtual function in sub-routine

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Base
{
  public: 
    virtual void func(){ sub_func();}
    virtual void  sub_func(){ cout<<"base\n";}
};

class Deprived: public Base
{
  public:
    void sub_func(){cout<<"deprived\n";}
};

int main()
{
  Base *P=new Deprived;
  p->func();
}


why does the polymorphism work in the sub-routine sub_func()?
Why wouldn't it?? What makes you think it shouldn't work?
Why would it not? sub_func is a virtual function..

[edit]To elaborate. When you call a virtual function, the program looks up the function that needs to be called in a table your object holds. It doesn't matter at all where you call the method from. The program will look at the table *this has and decide whether to call Base::sub_func or Deprived::sub_func.[/edit]

By the way, why "deprived" ? pun or typo ?
Last edited on
Topic archived. No new replies allowed.