What is the output of the following C++ program?
#include<stdio.h>
[gamipress_button type=”submit” label=”Run Code Online” onclick=”window.open(‘https://coderseditor.com’,’_blank’)”]
#include<iostream> using namespace std; class base { public: virtual void show() { cout<<" In Base \n"; } }; class derived: public base { int x; public: void show() { cout<<"In derived \n"; } derived() { x = 10; } int getX() const { return x;} }; int main() { derived d; base *bp = &d; bp->show(); cout << bp->getX(); return 0; }
Output: Compiler Error: ‘class base’ has no member named ‘getX’
The above program contains a pointer of type “bp” that points to a derived object. Show() is available in base classes, so calling it through ‘bp’ is acceptable. Due to the fact that “show()” is virtual in the base class, it actually calls the derived class “show().” The call to getX(), however, is invalid because the base class does not contain getX(). Only those virtual methods of the derived class that are present in the base class can be accessed when a base class pointer points to a derived class object.