Jump to content
  • Advertisement
Sign in to follow this  
GraySnakeGenocide

Am I understanding the "virtual" keyword correctly?

This topic is 2481 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

Edit: Forgot to put C# in topic title

Using a base class, you define a virtual method, which allows you to override it in a derived class, enabling you to use that Method in a different manner?

Example:

Player class (base class)
public virtual void DoSomething()
{
this method involves the player moving
}

--------------------------------------------------
HumanPlayer class (derived class)

public override void DoSomething()
{
overriding the base method, we code enabling the player to move based on a particular button press.
}

----------------------------------------------------
AIPlayer class (derived class)
public override void DoSomething
{
overriding the base method, we code the AI to move between 4 directions, based on a Random.
}

Am I understanding this correctly?

I apologize for the shorthand/random code that doesn't really DO anything meaningful, just figured I'd whip something quick up

Share this post


Link to post
Share on other sites
Advertisement
Your example is incomplete. You don’t need virtuals to just do that.
If I have a pointer to an AIPlayer class instance, it will move randomly regardless of the virtual keyword.

The point of virtuals is that you don’t need to know the type of the object for those special versions of the functions to be effective.
If I have a list of pointers to Player class objects, virtual makes the difference between which of those functions is called when I actually called DoSomething() on a Player object.

The difference being that originally I had a pointer specifically to an AIPlayer, whereas later I had pointers only to Player objects, some of which were HumanPlayer and some of which were AIPlayer. Without virtual, you need to know the actual type of the object to make it do what you want.


L. Spiro

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • 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!