#include #include #include #include #include #include

how does c++ compiler handle "this" pointer in virtual function

108 Views Asked by At

i got a confuse about how does c++ compiler handle "this" pointer in virtual function, my code:

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <iostream>

using namespace std;



class A {
        public:
                void print_A(void) {
                        cout << "A::THIS = " << this << endl;

                        return;
                }

                int a;

        virtual ~A(void) {
                return;
        }
};

class B {
        public:
                virtual void print(void) {
                        cout << "B::THIS = " << this << endl;

                        return;
                }

                int b;
};

class C: public A, public B {
        public:
                void print(void) {
                        cout << "C::THIS = " << this << endl;

                        return;
                }

                int c;
};


class D {
        public:

                int d;

                virtual ~D(void) {
                        return;
                }
};


class E: public D, public C {
        public:
                int e;

                virtual ~E(void) {
                        return;
                }
};

void global_print(B *pb) {
        cout << "pb = " << pb << endl;
        pb->print();

        return;
}

int main(int argc, char *argv[]) {

        E e;
        A *pa = &e;
        B *pb = &e;
        C *pc = &e;
        D *pd = &e;
        E *pe = &e;


        cout << "pa = " << pa << endl;
        cout << "pb = " << pb << endl;
        cout << "pc = " << pc << endl;
        cout << "pd = " << pd << endl;
        cout << "pe = " << pe << endl;

        pb->print();
        pc->print();
        pe->print();


        global_print(&e);
        return 0;

this is result compiled with g++ in my linux:

pa = 0x7ffc1e7c7a80
pb = 0x7ffc1e7c7a90
pc = 0x7ffc1e7c7a80
pd = 0x7ffc1e7c7a70
pe = 0x7ffc1e7c7a70
C::THIS = 0x7ffc1e7c7a80
C::THIS = 0x7ffc1e7c7a80
C::THIS = 0x7ffc1e7c7a80
pb = 0x7ffc1e7c7a90
C::THIS = 0x7ffc1e7c7a80

I can't understand that i send &e to global_print and pb in global_print is equal to 0x7ffc1e7c7a90. And then i invode pb->print(), the this pointer in global_print is 0x7ffc1e7c7a80 which is equel to pc. It seems that the pb->print() convert class B to class C, but class B is the father class of class C, how dose it convert?

And although pb can get addres of C::print by virtual function, it's only a address that havn't enough information to konw that is need to convert class B to class C, so how does the program konw that need to convert class B to class C in the run time?

THANKS a lot! wish have a nice day!

0

There are 0 best solutions below