Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call derived method which does not exist in base class from base class

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;
}
like image 722
arch.wzy Avatar asked Oct 18 '25 13:10

arch.wzy


1 Answers

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 Spheres are Balls, and that one certainly isn't). This is Undefined Behaviour, and can do anything, including toasting your cat. Watch out.

like image 139
Quentin Avatar answered Oct 20 '25 05:10

Quentin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!