Dynamic method dispatching

T

Terry

Hi,

could someone please exmaplin to me what dynamic method dispatching is
and how it's connected to virtual methods? Thanks

Terry
 
J

John Harrison

Terry said:
Hi,

could someone please exmaplin to me what dynamic method dispatching is
and how it's connected to virtual methods? Thanks

Terry

Virtual methods use dynamic dispatching. This means that the method that is
called depends on the type at run time, not the type at compile time.

E.g.

class B
{
public:
virtual void func() { cout << "its B" }
};

class D : public B
{
public:
virtual void func() { cout << "its D" }
};

B* b_ptr = new D();
b_ptr->func();

Which func is called, B::func or D::func? At compile time b_ptr is a B* so
you could argue that B::func is called (static dispatching). But when the
program runs b_ptr happens to be pointing to a D, so you could argue that
D::func is called (dynamic dispatching).

The answer in this case is the D::func is called. Because func is virtual
dynamic dispatching is used. If func where not virtual then B::func would be
called.

Why don't you try it and see? Then remove virtual and try again.

john
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,009
Latest member
GidgetGamb

Latest Threads

Top