Daily Dose C++: Virtual Functions

Source

Geeks For Geeks: Virtual Functions

Dose

  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 {
    public:
        // Note: virtual keyword used here for function.
        virtual void print() { cout << "Base"; }
        void print2() { cout << "Base2"; }
};

class derivedObject: public baseObject {
    public:
        // 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;

    b->print();
    // Output : "Derived"

    b->print2();
    // Output: "Base2"
    // Since we didn't define print2 as 'virtual'

    // You can call the derived function directly
    d.print2();
    // Output: "Derived2"

    return 0;
}

You'll only receive email when they publish something new.

More from Wron
All posts