Constructor usage rules for C + + classes

Source: Internet
Author: User
Tags shallow copy

//constructor usage rules for classes#define_crt_secure_no_warnings#include<iostream>using namespacestd;classpointa{};classpointb{ Public: Pointb (intAarint_b,Const Char*pin/*inch*/) {x=_a; Y=_b; Remark= (Char*)malloc(sizeof(Char) * (strlen (PIN) +1));        strcpy (remark, PIN); cout<<"I'm a self-defined, parametric constructor. 4"<<Endl; }Private:    intx; inty; Char*remark;};classpointc{ Public: Pointc (POINTC&pm) {cout<<"I'm a custom copy constructor 3"<<Endl; //Modifying a copy constructorx =pm.x; Y=pm.y; //remark = Pm.remark; This sentence is wrong.//Modified ScenarioRemark = (Char*)malloc(sizeof(Char) * (strlen (Pm.remark) +1));    strcpy (remark, Pm.remark); }Private:    intx; inty; Char*remark;};voidProtecta () {Pointa P1;//Call the default parameterless constructorPointa P2=p1;//Call the default copy constructor// Conclusion ①: When no one constructor is defined in a class, the C + + compiler provides a parameterless constructor and a copy constructor//POINTB P3;//Error : Error C2512: "POINTB": no appropriate default constructor availablePOINTB P4 (3,3,"455");//calling a custom-defined parameter constructorPOINTB P5 = P4;//Call the default copy constructor// Conclusion ②: When an arbitrary non-copy constructor is defined in a class (no parameter, no parameter), the C + + compiler does not provide a parameterless constructor.//However, if any copy function is not defined in the class, the C + + compiler will still provide a default copy constructor//POINTC P6;//Error C2512: "POINTC": no appropriate default constructor available// Conclusion ③: When a copy function is defined in a class, the C + + compiler does not provide a default parameterless constructor// Conclusion ④: The default copy constructor is simply a simple assignment between class member variables (a shallow copy of the details reference class)}voidMain () {System ("Pause");}

Constructor usage rules for C + + classes

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.