CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2
  1. #1
    Join Date
    Oct 2007
    Location
    India
    Posts
    30

    Smile using of Virtual keyword

    Hi friends,

    I would like to know why virtual keyword is not used along with static, abstract, private, or override.. Can somebody explain it with an example ?
    Please help..

    Thanks in advance.. :-)

  2. #2
    Join Date
    Jan 2010
    Posts
    1,133

    Re: using of Virtual keyword

    To understand the virtual keyword, you have to be familiar with classes and inheritance. Are you?
    In any case, I've written an extensive explanation of both in response to another question - but it can work for you as well. Note, however, that it's intended to supplement whatever introductory reading material on classes and inheritance you already use(d), so if you are not familiar with these, please read up on them. An intro C# book or some online tutorials will do fine.

    Near the bottom of the post, there are two code sample downloads, the first of which (InheritanceExample) is relevant to you - it should help you understand everything nicely, and the code contains some comments that assume the reader has no experience with inheritance.

    As for your question, it's simple - virtual simply marks a method implementation as overridable in an inherited class, so:
    • static methods belong to the class itself (and not objects) and inheritance works on objects, so they cannot be overridden;
    • abstract is basically the same as virtual, except that it also demands that the method declared abstract has no implementation at all (as it is intended for derived classes to provide it);
    • private members of a class are not visible in an inherited class (only public and protected are), so they cannot be overridden;
    • override keyword specifies that an inherited method (that's either abstract or virtual) is overridden in a particular class; unless explicitly sealed, the same method can be overridden in further derivations, so it is basically virtual - no need to specify it again.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured