I was trying below code:
In which I am calling opengascap()
of car class with car*
pointer which is pointing to a object of nuclear**
class but it is giving nuclear***
function of the object that is being pointed to.
My question is why its giving output "fire" although the function name doesn't even exist in the nuclearsubmarine
class.
#include <iostream>
using namespace std;
class Vehicle
{
public:
virtual ~Vehicle() { }
virtual void startEngine() = 0;
};
class Car : public Vehicle
{
public:
virtual void startEngine()
{
cout<<"start car";
}
virtual void openGasCap()
{
cout<<"open";
}
};
class NuclearSubmarine : public Vehicle
{
public:
virtual void startEngine()
{
cout<<"start ship";
}
virtual void fireNuclearMissle()
{
cout<<"fire";
}
};
int main()
{
Car car;
Car* carPtr = &car;
NuclearSubmarine sub;
NuclearSubmarine* subPtr = ⊂
carPtr=(Car*)subPtr;
// This last line would have caused carPtr to point to sub !
carPtr->openGasCap(); // This might call fireNuclearMissle()!
return 0;
}
Ouput: fire