C ++ vtable Problems

Source: Internet
Author: User

(1) Impact of vtable

This increases the size of an object instance by 4 bytes.

# Include <cstdlib>
# Include <iostream>

Using namespace STD;

Class
{
Int;
};

Class B
{
Virtual void say ()
{
}

Int B;
};

Int main (INT argc, char * argv [])
{
A;
B;

Cout <"A:" <sizeof (a) <Endl;
Cout <"B:" <sizeof (B) <Endl;

System ("pause ");
Return exit_success;
}

 

Memset cannot be used for instances of objects containing virtual tables.
The generation time and location of the virtual table are affected by placement new.

# Include <cstdlib>
# Include <iostream>

Using namespace STD;

Class
{
Public:
A ()
{
Show ();
}

Virtual void show ()
{
Cout <"A" <Endl;
}
};

Class B: public
{
Public:
B ()
{
Show ();
}

Void show ()
{
Cout <"B" <Endl;
}
};

Int main (INT argc, char * argv [])
{
B;

System ("pause ");
Return exit_success;
}

(2) simulate vtable in C Language

 

# Include <cstdlib>
# Include <iostream>

Using namespace STD;

Void func1 (int)
{
Cout <"func1" <Endl;
}

Void func2 (int B)
{
Cout <"func2" <Endl;
}

Struct vtable
{
Void (* func) (int v );
};

Struct
{
Struct vtable;
Void show (int v)
{
Table. func (v );
}
};

Int main (INT argc, char * argv [])
{
A A, B;
A. Table. func = func1;
B. Table. func = func2;
A. Show (1 );
B. Show (1 );

System ("pause ");
Return exit_success;
}

 

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.