samedi 3 décembre 2022

When does vptr is created

I had started learning c++ in which I came to know that if there is a virtual function in the base class then the vptr is created only in the base class & once the object of the class is created at run time then the vptr is set to point to the vtable of the class whose object is created.

But, when I printed the size of the empty class with virtual function then it comes out to be 8 bytes.

#include <bits/stdc++.h>
#include <iostream>
using namespace std;

#pragma pack(1)
class A{
  public:
      virtual void display(){
        cout<<"A Class"<<endl;
      }
};

class B: public A{
  public:
      void display(){
        cout<<"A Class"<<endl;
      }
        void show(){
          cout<<"B Class"<<endl;
        }
};

int main() 
{
    cout<<sizeof(A)<<" "<<sizeof(B);//8 8
    return 0;
}

Above is the code which I ran.

My Question is if vptr is created when the object is created at run time then why here size comes out to be 8 bytes even if the object of the class has not been created yet.

Also one more question that comes out is

#include <bits/stdc++.h>
#include <iostream>
using namespace std;

#pragma pack(1)
class A{
  public:
      virtual void display(){
        cout<<"A Class"<<endl;
      }
};

class B: public A{
  public:

};

int main() 
{
    cout<<sizeof(A)<<" "<<sizeof(B);
    return 0;
}

Here if I leave class B as empty then total how many vtables will be created here ?

I tried using std::is_polymorphic::value for verifying if vtable is created in the table or not but, I am not sure of this function.

Aucun commentaire:

Enregistrer un commentaire