In this example, I create base object sphere(2), and assign its address to a derived class pointer with type conversion. Then I can call the fun() function that does not exist in base object sphere(2). And I think it is quite strange, since this is no definition for fun() in Sphere at all. But I can make type conversion and call it. Can someone explain it? Thanks in advance.
PS: The output is "Haha I am a ball with radius 2"
//---------sphere.h--------------
#ifndef SPHERE_H
#define SPHERE_H
class Sphere{
private:
double _radius;
public:
Sphere(double radius){
_radius = radius;
}
double getRadius(){
return _radius;
}
};
#endif
//-----------ball.h--------------
#ifndef BALL_H
#define BALL_H
#include <iostream>
#include "Sphere.h"
using namespace std;
class Ball : public Sphere
{
private:
string _ballName;
public:
Ball(double radius, string ballName): Sphere(radius){
_ballName = ballName;
}
string getName(){
return _ballName;
}
void fun(){
cout << "Haha I am a ball with radius " << getRadius() << endl;
}
void displayInfo(){
cout << "Name of ball: " << getName()
<< " radius of ball: " << getRadius() << endl;
}
};
#endif
//-------main.cpp----------------
#include "Ball.h"
#include "Sphere.h"
int main(){
Ball *ballPtr;
Sphere sphere(2);
ballPtr = (Ball *)&sphere;
ballPtr -> fun();
return 0;
}
That was mere "luck". You are invoking a function on an object while pretending it is of another type (a Ball
is a Sphere
, but not all Sphere
s are Balls
, and that one certainly isn't). This is Undefined Behaviour, and can do anything, including toasting your cat. Watch out.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With