Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

When should C++ define the constructor

Shulou Source: shulou.com Published: 2022-06-01 19:11:49 10月05日 Update

This article mainly explains "when should C++ define the constructor", interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Next, let the editor take you to learn "when should C++ define a constructor"?

C.40: if the class contains invariants, define the constructor Reason (cause)

This is the purpose of the constructor.

Example (sample) class Date {/ / a Date represents a valid date

/ / in the January 1, 1900 to December 31, 2100 range

Date (int dd, int mm, int yy)

: d {dd}, m {mm}, y {yy}

{

If (! is_valid (d, m, y)) throw Bad_date {}; / / enforce invariant

}

/ /...

Private:

Int d, m, y

}

It is usually a good idea to represent invariants through Ensure in a constructor.

Note (Note)

For convenience, you can define a constructor for a class even if it does not contain invariants.

Struct Rec {

String s

Int i {0}

Rec (const string& ss): s {ss} {}

Rec (int ii): I {ii} {}

}

Rec r1 {7}

Rec R2 {"Foo bar"}; Note (note)

The initialization list of Clippers 11 eliminates the need for many constructors. For example:

Struct Rec2 {

String s

Int i

Rec2 (const string& ss, int ii = 0): s {ss}, I {ii} {} / / redundant

}

Rec2 R1 {"Foo", 7}

Rec2 R2 {"Bar"}

The constructor of Rec2 is redundant. At the same time, the default value of int provided by the member initializer will be better.

Enforcement (implementation recommendations)

If the class contains a user-defined copy operation but does not provide a constructor (a user-defined copy is an obvious sign that the class has an invariant)

At this point, I believe you have a deeper understanding of "when C++ should define the constructor". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Tags: Function time content copy user learning practical obvious deeper necessary idea interest reason at the same time practicality practicality that is suggestion necessity Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MariaDB Shulou Information OPPO Reno macOS Linux