By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
434,871 Members | 2,337 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 434,871 IT Pros & Developers. It's quick & easy.

What does this code do?

P: 29
can someone explain to me "what does this code do"

Expand|Select|Wrap|Line Numbers
  1. class baseclass
  2.    public:
  3.    virtual void runme()
  4.    {
  5.     std::cout<<"are you"<<std::endl;
  6.    }
  7. };
  8. class derivedclass :public bassclass
  9. {
  10.    public:
  11.    void runme()
  12.    {
  13.     std::cout<<"there"<<std::endl;
  14.    }
  15. }
  16. baseclass  *test_class =new Derivedclass();
  17. test_class->runme();
  18.  
does the code surpose to read out.
"are you there"
Jun 14 '07 #1
Share this Question
Share on Google+
1 Reply


weaknessforcats
Expert Mod 5K+
P: 9,197
The output is: there

Your object is a derivedclass object. This object has a virtual function table (VTBL) with the addresses of all virtual functions declared in the class or inherited. The derivedclass::runme() method has overriden baseclass::runme() so it is the address of derivedclass::runme() in the VTBL.

Therefor, it is derivedclass::runme() that is called when you use the derivedclass object with a baseclass pointer or reference.

This is basic polymorphism. A program using polymorphism is an object-oriented program.
Jun 14 '07 #2

Post your reply

Sign in to post your reply or Sign up for a free account.