c++ - Call derived method which does not exist in base class from base class -


In this example, I make the original object globular (2), and the class pointers generated with one type of conversion Assigns your address. Then I can call the fun () function which is not present in the base object area (2). And I think that this is quite strange, because there is no definition for fun (). But I can type typed and call it. Can anyone explain this? Thanks in advance.

PS: Output "Haha I'm a ball with radius 2"

  // --------- sphere.h ---- - --------- #ifndef SPHERE_H # Defined SPHERE_H square area {Private: Double _radius; Public: Area (double radius) {_radius = radius; } Double getRadius () {return _radius; }}; #endif // ----------- -ball .h ..---------- #ifndef BALL_H # Defined BALL_H # contains & lt; Iostream & gt; # Include "Sphere.h" using the namespace std; Class ball: public sector {private: string _ball name; Public: Ball (Double Radius, String Bottle Name): Area (Radius) {_ballName = ballName; } String getName () {Return _ballName; } Zero Fun () {cout & lt; & Lt; "Haha I'm a ball with radius" & lt; & Lt; GetRadius () & lt; & Lt; Endl; } Zero performance INFO () {cout & lt; & Lt; "Ball Name:" & lt; & Lt; GetName () & lt; & Lt; "Radius of the Ball:" & lt; & Lt; GetRadius () & lt; & Lt; Endl; }}; #endif //-------main.cpp---------------- #include "Ball.h" #Include "Sphere.h" int main () {Ball * BallPtr; Regional area (2); BallPtr = (ball *) and field; BallPtr - & gt; Fun (); Return 0; }    

That was the only "luck". You are starting a function on an object, while showing it another type (a ball a sphere , but all the sphere S balls , and that is not one definite). It is undefined behavior , and can do anything, including your cat's toast.

Comments

Popular posts from this blog

ios - Adding an SKSpriteNode to SKScene from a child SKSpriteNode -

Matlab transpose a table vector -

c# - Textbox not clickable but editable -