In C ++, how does the default (copy) constructor handle the content of the four bytes in the class object that point to the vtable? (2)

Source: Internet
Author: User

# Include <iostream>
# Include <vector>
# Include <iterator>
Using namespace STD;

Class cbase
{
Public:
Virtual void FN ()
{
;
}
Virtual void add (cbase B)
{
}
Virtual void add (cbase * pb)
{
}
Cbase (const cbase & B)
{
: Memcpy (void *) This, (void *) & B, sizeof (cbase ));
}
Cbase & operator = (const cbase & B)
{
: Memcpy (void *) This, (void *) & B, sizeof (cbase ));
Return * this;
}

Cbase ()
{
}
};

Class cpart: Public cbase
{
Public:
Void FN ()
{
Cout <"P: FN" <Endl;
}

};

Class ccom: Public cbase
{
Public:
Void FN ()
{
Cout <"com: FN" <Endl;

Vector <cbase >:: iterator ITB, ite;
ITB = This-> m_vb.begin ();
ITE = This-> m_vb.end ();//
For (; ITB! = Ite; ++ ITB)
(* ITB). FN ();
}
Void add (cbase B)
{
M_vb.push_back (B );
}
Virtual void add (cbase * pb)
{
M_pvb.push_back (PB );
}
Protected:
Vector <cbase> m_vb ;//
};

Int main (INT argc, char * argv [])
{
Cpart P1, P2, P3, P4;
Ccom C1, C2;
Cbase * pb = & P1;
Pb-> FN ();
PB = & C1;
Pb-> Add (P1 );
Pb-> Add (P2 );
Pb-> Add (P3 );
Pb-> FN ();
Return 0;
}

 

Output:

P: FN

COM: FN

P: FN

P: FN

P: FN

// Tool used: vc6

We force modify the pvtbl of the object (that is, the pointer to the vtable ). So even the object can be used to achieve polymorphism ,,

But don't forget platform relevance.

In addition, we usually do not modify pvtbl !!

Related Article

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.