Daily Dose C++: Virtual Functions


Geeks For Geeks: Virtual Functions


  1. Polymorphism achieved through runtime.
  2. Bound through using a pointer to a class object.
  3. Need to use the keyword virtual to enable usage of virtual function
  4. Since the derived object is related to the base object, you can pass a pointer to derived thorugh the base object.
  5. Regardless, the base object will know to use the derived object.
class baseObject {
        // Note: virtual keyword used here for function.
        virtual void print() { cout << "Base"; }
        void print2() { cout << "Base2"; }

class derivedObject: public baseObject {
        // can be reached from base object
        void print() { cout << "Derived"; }

        // cannot be reached from base object
        void print2() { cout << "Derived2"; }

int main(){

    baseObject* b;
    derivedObject d; 
    b = &d;

    // Output : "Derived"

    // Output: "Base2"
    // Since we didn't define print2 as 'virtual'

    // You can call the derived function directly
    // Output: "Derived2"

    return 0;

You'll only receive email when Wron publishes a new post

More fromĀ Wron