Virtual Function

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • azey
    New Member
    • Jul 2008
    • 1

    Virtual Function

    Why constructor can not be make virtual while destructor can be virtual
  • gpraghuram
    Recognized Expert Top Contributor
    • Mar 2007
    • 1275

    #2
    Virtual comes into picture only after the object gets created.
    So we cant have a virtual constructor to create the object.

    raghu

    Comment

    • weaknessforcats
      Recognized Expert Expert
      • Mar 2007
      • 9214

      #3
      Virtual has several meanings in C++ depending on where you find it.

      For derived objects that are used in functions expecting base object pointers or refereences, the virtual tells the compiler that if there is a choice between the base class method orthe derived class method, that the derived method is to be used.

      For destructors, it tells the compiler that even though I ask you to delete the deirved object by deleting a pointer to the base class, the compiler is to call the deirved class destructor. If the destrcutor is not virtual, when you delete a derived object by deleting it using a base class pointer ot refererence, only the base class part of the object is cleaned up. Any allocations you made in the derived class are not cleaned up and you leak.

      For inheritance, a virtual base class tells the compiler that there is to be only one base object inside the derived object.

      The problem with virtual for beginners is the assumption that is means the same thing all the time. Part of the problem was the ANS C++ committee refusing new keywords in C++ for new situations. Hence, virtual has three meanings.

      Comment

      Working...