[CPP]Default members and conversion
Default member functions
Automatically generated functions
- 4 functions created by default if needed
- You can make them unavailable(e.g. private)
- Or change their behaviour
- A default constructor (no parameters needed)
- A copy constructor(copy one object to another)
- An assignment operator ( = operator)
- A destructor
A default constructor
- Automatically created if and only if you do not create any other constructors
- This is why you can still create objects even when classes appear to have no constructors
- If you create any constructor, compiler will not create a default one for you.
- Since C++ 11 you can tell it to create a default one anyway by putting “= default” instead of “{}”
ClassName() = default;
- if we comment on “DemoClass() = default;” This program will not compile.
The copy constructor
The copy constructor is used to initialize one object from another of the same typeThis includes when a copy is implicitly made:
- Passing object as a parameter into a function
- Returning object by value from a function
- Takes a constant reference to the object to copy from
- Has to be a reference!(to avoid needing to copy)
- If not a reference then copying parameter value means copying the object
Assignment operator
- Used when value of one object is assigned to another
- Assignment operator will be created by default
- Takes a reference to the one we are getting values from
- Returns a reference to *this, so we can chain these: ob1= ob2 = ob3;
Above is a every interesting code: - We create demoClass1 use default constructor, so demo1 will print “1”
- We create demo2 using constructor, will print “2”
- We make a copy constructor on demo3, it will add i to 1, so will print “3”
- We create demo4 and using assignment operator, so will print “12”
- then we create demo5, 6 and 7
- We chain them, we first look at the right hand side, demo7 is “6”, so demo6 is “16” and demo5 will be “26”
Destructor
- A destructor is created if you do not create one yourself
- Default destructor does nothing
Conversion constructors
A conversion constructor is a constructor with one parameter.It is a normal constructor but with single parameter, so we can pass this parameter when initializing:
Keyword “explicit”
- Providing a one-parameter constructor provides a conversion constructor
- This allows compiler to use it to convert to the type whenever it wants/needs to do so
- To avoid this, use the keyword explicit
- Then you CAN NOT USE = parameter to initialize
Conversion operator
- Convert from a class into something else(like int, float)
- Uses operator overloading syntax
If you don't want the default constructor, in C++11, you can use "ClassName() = delete;"
回复删除