what is diffrence between virtual and pure virtual?
What is the difference between virtual and pure virtual?
Collapse
X
-
Tags: None
-
An abstract class with a (or more) pure virtual methods cannot be instantiated:
Any child class needs to override this method. Therefore with pure virtual methods you must override them (if you want to instantiate the class), and virtual methods may or should be overridden.Code:class Abstract { public: virtual void pure_virtual() = 0; }; -
Virtual Function:
Used to put the address of the member function into the VTBL. Note that if a derived object is accessed using a base class pointer, the VTBL will have the address of the derived class method. Therfore, the derived class method will be called.
Pure Virtual Function:
A member function that cannot be called using an object of the class that declares it. This applies to virtual functions only. This allows the base class to define the interface functions for the hierarchy leaving the implementation to the derived classes.Comment
-
What is difference between abstract method and virtual method?
Virtual method has an implementation & provide the derived class with the option of overriding it.
Abstract method does not have an implementation & forces the derived class to override the method.
In Virtual method, The key word ‘virtual’ need to be used in method signature.
In Abstract method, The key word ‘abstract’ need to be used in method signature.
Virtual can be defined in any class.
Abstract method can be defined in only Abstract Class.
Example:
public abstract class Test
{
// Abstract method
public abstract void A();
// Virtual Method
public virtual void B() {
Console.WriteLi ne("Test.B");
}
}
public class InheritedTest : Test
{
public override void A() {
Console.WriteLi ne("InheritedTe st.A");
}
//Method B implementation is optional
public override void B()
{
Console.WriteLi ne("InheritedTe st.B");
}
}Comment
-
Comment