Home > Back-end >  This pointer
This pointer

Time:12-01

# include & lt; Iostream>
using namespace std;

The class parent
{
Public:
Void fun (parent * p)
{
Cout & lt; <"Pointer address is:" & lt;

Cout & lt; <"This pointer address is:" & lt; }
The parent (void)
{
}
};
The class parent2
{
Public:
Void fun2 (parent2 * p)
{
Cout & lt; <"2 address pointer is:" & lt;

Cout & lt; <"This2 pointer address is:" & lt; }
Parent2 (void)
{
}
};
The class son: public parent2, parent
{
Public:
Void sonFun (void)
{
Cout & lt; <"The current pointer address is:" & lt; Fun (this);
Fun2 (this);
Cout & lt; <"Pointer address is:" & lt; }
};

Void main (void)
{
Son s;
S.s onFun ();
While (1);
}


Why do fun and fun2 can pass this pointer, this pointer is not point to objects of son itself?

CodePudding user response:

This is the foundation of polymorphism, can put a parent class pointer to a subclass object,

CodePudding user response:

The following can understand?
Class A, {}.
The class SA: public A {};
A * A=new SA (); SA//parent class reference point to a subclass object (new SA return this is pointing to a subclass of this assignment to a, since this can be assigned to a, the parameter is also ok)

CodePudding user response:

So to understand? Subclass=total memory size of the parent class memory size + subclasses of memory size and your program A * A=new new SA SA () here () A pointer just the pointer to the head of the parent class

CodePudding user response:

I now the question is fun (this); This pass this pointer is understandable, but fun2 (this); How can pass the word of this pointer is not understood, because fun2 need parent2 pointer, parent2 pointer inside the object s son is offset, and fun2 transfer inside the this pointer is offset correctly! This is what happened?


CodePudding user response:

reference 4 floor NexyHo response:
I the problem now is fun (this); This pass this pointer is understandable, but fun2 (this); How can pass the word of this pointer is not understood, because fun2 need parent2 pointer, parent2 pointer inside the object s son is offset, and fun2 transfer inside the this pointer is offset correctly! This is what happened?


Tracking the use debug tracking mode, see,
By the way, have a look at the disassembly code,
  • Related