A easy problem about Polymorphic

O

Osamede.Zhang

Compiler store a pointer table in each object with virtual fuction to
implement polymorphic,isn't it? But where is the pointer table?
It seems that object only store a pointer to the table,the output of
this code is 88.
#include<iostream>
using namespace std;
class MyClass{
public:
MyClass(){ a=0;}
virtual void tst1() {a-=1;}
virtual void tst2(){a*=2;}
virtual void tst3(){a*=1;}
private:
int a;
};
class Tst:public MyClass{
void tst1() {std::cout<<"Tst"<<endl;}
void tst2(){std::cout<<"Tst"<<endl;}
void tst3(){std::cout<<"Tst"<<endl;}
};
int main()
{
//Tst tstObject;
//MyClass *tstp=&tstObject;
//tstp->sub();
Tst tstObject;
MyClass myObject;
cout<<sizeof(myObject);
cout<<sizeof(tstObject);
return 1;
}
 
B

Bluse.huang

when base class has virtual functions, a v_ptr that point to the
v_table will be add
so, the object's size is the sizeof(v_ptr) + sizeof(data member)


"Osamede.Zhang дµÀ£º
"
 
O

Osamede.Zhang

"Bluse.huang дµÀ£º
"
when base class has virtual functions, a v_ptr that point to the
v_table will be add
so, the object's size is the sizeof(v_ptr) + sizeof(data member)
But where is v_table ?heap??textseg?
 
R

Ron Natalie

Osamede.Zhang said:
Compiler store a pointer table in each object with virtual fuction to
implement polymorphic,isn't it? But where is the pointer table?
It seems that object only store a pointer to the table,the output of
this code is 88.
Making a class polymorphic (at least one virtual function) is
likely to incur overhead. The nature of the overhead is
implementation specific. While vtables and vptrs are a
common way to do this, do not be fooled into believing that
this is defined by the language.

In the common implementation, each object of a polymorphic
type will have a pointer to a table. Each defined class
will create this table somewhere in memory and set it's
objects pointer to it during construction.
 
R

Ron Natalie

Bluse.huang said:
when base class has virtual functions, a v_ptr that point to the
v_table will be add
so, the object's size is the sizeof(v_ptr) + sizeof(data member)
There might also be some padding. The object size is not necessarily
the sum of it's non-static members.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,763
Messages
2,569,562
Members
45,038
Latest member
OrderProperKetocapsules

Latest Threads

Top