May be the below questions are a bit naive, but they are confusing me as so I asked.
There 3 questions here below:
1) When does actually a virtual table gets created at compile time or runtime?
class base
{
int b;
public:
base()
{
printf("Base Cons\n");
}
virtual void show(void)
{
printf("Base Show\n");
}
};
class der: public base
{
int d;
public:
der()
{
printf("Der Cons\n");
}
void show(void)
{
printf("Der Show\n");
}
};
void fn_base(void)
{
base bobj;
.
.
.
}
void fn_der(void)
{
der dobj;
.
.
.
}
int _tmain(int argc, _TCHAR* argv[])
{
int option = 0;
scanf("%d",&option);
if(option == 1)
{
fn_base();
}
else
{
fn_der();
}
return 0;
}
In the above example the object will be created at runtime so will when does actually a virtual table gets created at compile time when I define the class or runtime when I create the objects?
2) We know sizeof is a compile time operator.
Consider below the same above example but modified a little:
class base
{
int b;
public:
base()
{
printf("Base Cons\n");
}
virtual void show(void)
{
printf("Base Show\n");
}
};
class der: public base
{
int d;
public:
der()
{
printf("Der Cons\n");
}
void show(void)
{
printf("Der Show\n");
}
};
void fn_base(void)
{
base bobj;
printf("%d\n",sizeof(bobj));
}
void fn_der(void)
{
der dobj;
printf("%d\n",sizeof(dobj));
}
int _tmain(int argc, _TCHAR* argv[])
{
int option = 0;
scanf("%d",&option);
if(option == 1)
{
fn_base();
}
else
{
fn_der();
}
return 0;
}
Above we are calling sizeof() in fn_base() and fn_der() at runtime.
But sizeof being a runtime operator how will it return the size when called from functions at runtime?
3) I have read that it gets created when we create an object of the class having virtual function. Will it get created even if I do not create any object of the class having virtual function?
Consider the following example:
class base
{
int b;
public:
base()
{
printf("Base Cons\n");
}
virtual void show(void)
{
printf("Base Show\n");
}
};
class der: public base
{
int d;
public:
der()
{
printf("Der Cons\n");
}
void show(void)
{
printf("Der Show\n");
}
};
int _tmain(int argc, _TCHAR* argv[])
{
return 0;
}
Will the virtual table get created here?