Home > Back-end > Weak ask everyone: why can subclass object pointer to the parent class of the object pointer assignm
Weak ask everyone: why can subclass object pointer to the parent class of the object pointer assignm
Time:10-01
The Person * Person=new Student (); Among them the Person class is the parent class Student class, why why subclass object pointer to the parent class object pointer assignment? Isn't the first cast to subclass object pointer to the superclass object pointer, and then give the person a pointer assignment?
CodePudding user response:
For a long time before I'm not sure, this is to subclass object assignment to the parent class, parent can point to a member of the subclass inherits the parent class, and members of the virtual function to rewrite, but cannot point to subclass unique members, As if such
CodePudding user response:
If not the assignment, polymorphism and how to implement the
CodePudding user response:
A certain type of pointer can point to its type variable, if not you need to type conversion
But in order to achieve the polymorphism, must base class pointer to a derived class object, so the compiler will acquiesce in this kind of behavior
CodePudding user response:
The Student is also a Person But the Person is not necessarily the Student
CodePudding user response:
Superclass object pointer can cast to subclass object pointer? For example: The Person * Person=new Person (); Student * Student=(Student *) person;