Type retrieved by the this keyword

Okay...

I was wondering about something related to pointers, polymorphism, and the keyword "this". If I do something like,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class celestial_body
{...
};

class Star: public celestial_body
{...
};

class Planet: public celestial_body
{...
};

celestial_body * Sol, * Earth;
Sol = new Star(); 
Earth = new Planet();


What would the type of the pointer be if I set up a function to get whatever is returned by the this keyword in the Star and Planet classes? Is it of the type celestial_body (the parent class), or of Planet (or Star, the derived class)

It just doesnt seem right for me to be able to get pointers of two different types from the same object.
The type of the this pointer is the same as the class that the member function belongs to. The return type of the function is what you choose it to be.
So, the derived one then?
If you are in a member function that is in a derived class, then this will be a pointer to the derived class.

If you are in a member function that is in the parent class, then this will be a pointer to the parent class.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class celestial_body
{
    void a()
    { /* 'this' is a pointer to a celestial_body */  }
};

class Star: public celestial_body
{
    void b()
    { /* 'this' is a pointer to a Star */  }
};

class Planet: public celestial_body
{
    void c()
    { /* 'this' is a pointer to a Planet */  }
};
Topic archived. No new replies allowed.