如果g ++编译器是基类中的多个vtable ptr,它们如何知道要使用哪个vtable ptr?

时间:2014-10-13 03:09:20

标签: c++ oop compiler-construction g++ vtable

我想知道如果g ++编译器在基类中存在多个vtable,它们如何知道要使用哪个表。像下面的例子。

#include<cstdio>
#include<iostream>
#include<cstdlib>
#include<cstring>

using namespace std;

class sample1
{
private:
    int b;
public:
    sample1():b(34)
    {
        cout << "In sample1 constructor" << endl;
    }
    virtual void print_b()
    {
        cout << this->b << endl;
    }
    void print_all()
    {
        this->print_b();
    }
    void sample_print_()
    {
        //cout << this->a << "String : " << this->str1 << endl;
        cout << "hello" << endl;
        this->print_all();  
    }
 };

class sample2
{
private:
    int b1;
public:
    sample2():b1(34)
    {
        cout << "In sample1 constructor" << endl;
    }
    virtual void print_b1()
    {
        cout << this->b1 << endl;
    }
    void print_all1()
    {
        this->print_b1();
    }
};

class sample : public sample1 , public sample2
{
private:
    int a;
    char *str1;

public:
sample():a(12),sample1()
{
    strcpy(this->str1,"hello world");
    cout << "In Constructor" << endl;
}
~sample()
{
    free(this->str1);
    cout << "In Destructor" << endl;
}
void sample_print()
{
    //cout << this->a << "String : " << this->str1 << endl;
    cout << "hello" << endl;
    this->print_all();
}
    virtual void print_a()
    {
      cout << this->a <<endl;
    }
};

在上面的例子中,子类示例有两个父类sample1和sample2,每个类都有自己的vtable。如果我从样本(子类)调用虚函数怎么办?编译器如何知道虚拟函数存在于哪个类中,以便它调用使用特定的vtable指针?我知道他们将是样本(子类)类中的两个vtable指针,那么编译器如何知道使用哪一个?

0 个答案:

没有答案