C++ GFG Constructor and Destructor + Function Overloading
Explicit example
'explicit' doesn't allow implicit conversions. In this case, '3.0' is not type 'Complex' so '==' doesn't work.
Copy elision
A compiler optimization technique that avoids unnecessary copying of objects.
Copy constructor vs assignment operator
Copy constructor: when a new object is created from an existing object Assignment operator: when an already initialized object is assigned a new value from another existing object
Example of constructor and copy constructor
Copy elision performed for: B a = "copy me" //into B a ("copy me")
When do we need to define our own copy constructor?
Default copy constructor copies these members with an address of dynamically allocated memory and not a real copy of this memory. Now both the objects points to the same memory and changes in one reflects in another object (shallow copy).
Overloading functions with const parameters using &
Function has to pass by reference for 'const' to be overloaded.
If Base and Derived classes have functions with same names
Function overloading will not happen. The function in the derived class will be executed.
Destructor is executed
Only at the end of the block scope.
static
Static objects are initialized only once and live until the program terminates.
When we define our own parameterized constructor
The class doesn't create a default constructor.
When initializing members through constructor
Use the initializer list ClassName(int i = 0, int j = 0) : x(i), y(j) {} It saves trouble.
Purpose of private destructors
When destructors are private, only dynamic objects can be created like: Test* ptr = new Test; Now can control the destruction of objects in a class.
Overloading error with pointer and array
int fun(int *ptr); int fun(int ptr[]); //-> same as int *ptr