Daily Dose C++: Virtual Functions
February 12, 2021•177 words
Source
Geeks For Geeks: Virtual Functions
Dose
- Polymorphism achieved through runtime.
- Bound through using a pointer to a class object.
- Need to use the keyword
virtual
to enable usage of virtual function - Since the derived object is related to the base object, you can pass a pointer to derived thorugh the base object.
- 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;
}