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;

CodePudding user response:

reference 5 floor fangx0316 reply:
superclass object pointer can cast to subclass object pointer? For example:
The Person * Person=new Person ();
Student * Student=(Student *) person;

The Person is not necessarily a Student, so there will be a conversion fails,

Turn the parent class subclasses need to use dynamic_cast, strong turn is wrong,

CodePudding user response:

reference 5 floor fangx0316 reply:
superclass object pointer can cast to subclass object pointer? For example:
The Person * Person=new Person ();
Student * Student=(Student *) person;


Can, programmers want to responsible for the consequences,
In terms of the above procedures, would probably happen in behavior,

CodePudding user response:

Four conversion of c + + dynamic_cast dynamic conversion, is specialized in inheritance system transformation of
Derived class (a pointer, reference) can be implicitly converted to a base class (a pointer, reference),
Is one of the basic features of object-oriented
On which all polymorphism, to the realization of the convenient

CodePudding user response:

With c + + object model

CodePudding user response:

Student is a person, is a subclass of the parent class a, give him a pointer assignment problem,

CodePudding user response:

No, so subclasses can call the superclass does not exist in the method of function
  • Related