Copy Constructor and It's Types in C++
Copy Constructor and It's Types in C++
Programming Techniques
Task from Previous Lecture
• Implement a class that sets time to both 24 hour format and 12 hours
(from 00 to 11:59 = AM and from 12 noon to 23:59 = PM). Once time
is entered, it can’t be changed
Output
Copy Constructor
• Shallow Copy Constructor
• Deep Copy Constructor
Shallow Copy Constructor
• A shallow copy constructor is custom-defined
• It copies the values of the member variables directly, without
creating new copies of dynamically allocated resources (e.g.,
pointers)
• explicitly created
Example
Other
way
Assignment
Constructor
operator copies
copies
Output
Deep Copy Constructor
• A deep copy constructor is custom-defined
• It not only copies the values of member variables but also
creates new copies of dynamically allocated resources to avoid
shared ownership
Output
Output
Dry Run and Find Output
Output
Static Variable
• The space for the static variable is allocated only one time and
this is used for the entirety of the program
• The lifetime of a static variable is the lifetime of the program
Static Variable Examples
Output
Find Output
Static Data Members
• Static data members are class members that are declared
using static keywords
• Only one copy of that member is created for the entire class and is
shared by all the objects of that class, no matter how many objects
are created
• It is initialized before any object of this class is created, even before
the main starts
• It is visible only within the class, but its lifetime is the entire program
Static Data Members
int foo::count = 0; is the initialization of the static
member variable count outside of the class
Output
Output
Static Function Members
• We have static member functions that are used for a specific
purpose
• A static function can only access other static variables or
functions present in the same class
• Static member functions are called using the class name
• Syntax
class_name::function_name( )
Output
Output