Question: I have a class `sub` which inherits from a class `super`. They both define a function `void function()` (so the function in `sub` overrides that in `super`). I create a `super` pointer and assign it a new instance of `sub`. I then call `function()` on the instance of `sub` through the `super` pointer. However, the function in `super` is called, not that in `sub`. I want it to call the function in `sub`, not that in `super`. How should I do this?

```
#include <cstdio>  

class super {  
    public:
    void function() {  
        printf("Super\n");  
    }  
};  

class sub: public super {  
    public:  
    void function() {  
        printf("Sub\n");  
    }  
};  

int main() {  
    super *p;  
    p = new sub;  
    p->function();  
    return 0;  
}

```

Answer: 
The declaration should be:

```
virtual void function()

```

I'm rusty on C++, but basically if the function isn't virtual, the compiler will take you on your word that if the pointer is to a super, the function() call goes to super::function(). Virtual tells it that you want it to figure out the right one instead. In practice, this means it'll create a vtable instead, and do an indirect lookup. Then it doesn't matter whether it's a super\* or sub\*, because they will both have a vtable, and the vtable will point to the right version of function() for the actual type of the object.
```
class super {  
    public:
    virtual void function() {  
        printf("Super\n");  
    }  
};

```