Jump to content
  • Advertisement

Archived

This topic is now archived and is closed to further replies.

pschmitt

Virtual Function tutorial???

This topic is 5718 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Anyone know of a good site for a virtual function tutorial? We covered them for 10 minutes in my "advanced C++" class... I had a horrible teacher who didn''t speak English & was hired 2 days before class began. needless to say, I didn''t learn much. Thanks, -Pete

Share this post


Link to post
Share on other sites
Advertisement
Virtual functions simply allow you to choose the actual function to call based on the type at runtime.

So, given

  
class Base
{
public:
virtual void func1()
{
cout<<"Base::func1()"<<endl;
}
void func2()
{
cout<<"Base::func2()"<<endl;
}

};

class Derived: public Base
{
public:
virtual void func1()
{
cout<<"Derived::func1()"<<endl;
}
void func2()
{
cout<<"Derived::func2()"<<endl;
}

};

That creates a class heirarchy. Notice that func2 is not virtual - it will use the static type when we call it. func1 is virtual - it will use the dynamic type when we call it.
What is this static and dynamic type? Well, a base class pointer(or reference) can point to a derived class object:

  
Base* pBase;
pBase = new Base();
pBase->func1(); //prints Base::func1

pBase->func2(); //prints Base::func2

pBase = new Derived();
pBase->func1(); //prints Derived::func1

pBase->func2(); //prints Base::func2

Derived* pDerived;
pDerived = new Derived();
pDerived->func1(); //prints Derived::func1

pDerived->func2(); //prints Derived::func2



So why is this useful? If you have a collection of similar objects, and want them to behave differently at runtime, you can have a virtual function in the base class. Then, you can call this virtual function on all your objects, and the appropriate version will be called at runtime:

  
std::vector<Base*> objects;
objects.push_back(new Base());
objects.push_back(new Derived());
for(int i=0;i<objects.size();i++)
{
objects[i]->func1();
}
//prints Base::func1, Derived::func1

Share this post


Link to post
Share on other sites

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!