Memset Initialization Class error parsing when calling virtual functions

Source: Internet
Author: User

Occasionally in the group saw a piece of code problem, I knocked the next try to summarize; code:
#include <cstring>
#include <iostream>
Using namespace Std;class parent{public    :        Parent () {}        virtual void output ();}; void Parent::output () {    cout << "Parent" << Endl;} Class Son:public parent{public    :        virtual void output ();}; void Son::output () {    cout << "son"  << Endl;} int main () {    son s;    Memset (&s,0,sizeof (s));    Parent &p = s; The comment can be opened in error with the    Parent p;    P.output ();    S.output ();    return 0;}


The analysis is as follows:
There is usually no error when using memset for initialization, but if the internal structure is changed,  there is an error, and each class containing a virtual function has a pointer to the virtual table function, which is overwritten when memset. Therefore, the invocation of a virtual function bound by the runtime causes the program to crash if the call to bind does not run properly, so the constructor is initialized when there is a virtual function with the parent class reference to the subclass object;

Ubuntu Error Situation:

Memset Initialization Class error parsing when calling virtual functions

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.