Lect02 CPP More Class
Lect02 CPP More Class
2022
Contents
1. Constructors
2. Destructor
3. Member Initialization
4. Copy Constructor
5. Unnamed Object
6. Static Members
7. Friends of Classes
8. Workshop
Object Life Cycle
Constructors
Destructor
Member
Initialization
Copy
Constructor
Unnamed
Object
Static Members
Friends of
Classes
Workshop
3
Constructors
Constructors
Constructors
Destructor
Member
Initialization
Copy
Constructor Concept 1
Unnamed A constructor is a special member function that is automatically called when a
Object
Static Members
class object is created.
Friends of
Classes • Remember that when we define a local variable (primary data type) in C++,
Workshop the memory is not automatically initialized.
Constructor,
• It is automatically invoked when a new object is created.
• There is no returned value, even a void.
• A class can have more than one constructor (overload)
• Name of the constructors must be the same as the class name.
5
Declaring and Implementing a Constructor
Constructors
Destructor
Member
Initialization
Copy
Constructor class Human {
Unnamed
public :
Object Human () {
Static Members // constructor code here
Friends of Name = "Le Thi Dep";
Classes
DateOfBirth = " 01/01/1990 ";
Workshop
PlaceOfBirth = "Ha noi";
Gender = " female ";
}
...
};
6
When and How to Use Constructors
Constructors
Destructor
Member
Initialization
Unnamed
such as integers, pointers, and so on to known initial values
Object
7
When and How to Use Constructors (cont.)
Constructors
Destructor
Member
Initialization
8
When and How to Use Constructors (cont.)
Constructors
Destructor
Member
Initialization
Friends of
Classes
Workshop
9
Overloading Constructors
Constructors
Destructor
Member
Initialization
Copy • Default constructor (if no constructor is implemented, the compiler will issue
Constructor
Unnamed
a default constructor; if there is at least one constructor, the default
Object constructor will not be created by the compiler)
Static Members
• No parameters
Friends of
Classes • Invoke other default constructors of data members if they are objects.
Workshop • Doesn’t initialize other data members if they are not objects.
• Constructor with no parameters
• Constructor with parameter(s)
• Constructor with default parameter(s)
• Copy constructor
10
Example
Constructors
Destructor
Member
Initialization
Unnamed
constructor that requires Human to be created with a name as a parameter,
Object for instance:
Static Members
11
Class Without a Default Constructor
Constructors
Destructor
Member
Initialization
Copy
Constructor class CDate int main () {
Unnamed { CDate today; // compile error
Object public: ...
Static Members CDate(int day , int month , int year) return 0;
Friends of
; }
Classes ...
private:
Workshop
...
};
12
this Pointer
Constructors
Destructor
Member
Initialization
Copy
Constructor Concept 2
Unnamed this is a reserved keyword applicable within the scope of a class that contains the
Object
Static Members
address of the object. In other words, the value of this is &object
Friends of
Classes • this is a constant pointer, we cannot modify it within a member function.
Workshop
class Human {
...
void SetAge (int HumansAge ) {
this ->Age = HumansAge ; // same as Age = HumansAge
}
...
}
13
sizeof() a Class
Constructors
Destructor
Member
Initialization
Copy
Constructor Concept 3
Unnamed The operator sizeof() is valid for classes and basically reports the sum of bytes
Object
Static Members
consumed by each data attribute contained within the class declaration.
Friends of
Depending on the compiler we use, sizeof() might or might not include padding
Classes for certain attributes on word boundaries.
Workshop
int main () {
Human Tom;
cout << " sizeof ( Human ) = " << sizeof (Human) << endl;
cout << " sizeof (Tom) = " << sizeof (Tom) << endl;
}
14
Destructor
Destructor
Constructors
Destructor
Member
Initialization
Copy
Constructor Concept 4
Unnamed A destructor is a member function that is automatically called when an object is
Object
Static Members
destroyed.
Friends of
Classes • Destructor is always invoked when an object of a class goes out of scope or is
Workshop deleted via delete and is destroyed
• Each class can have at most one destructor
• The destructor name is the name of a class preceded by a tilde sign (~)
• Destructor has no return type (even void)
• Destructor frees the resources used by the object (allocated memory, file
descriptors, semaphores etc.)
16
Example
Constructors
Destructor
Member
Initialization
Unnamed
Object class Human {
Static Members
public :
Friends of
~Human () {
Classes // destructor code here
Workshop }
};
17
When and How to Use Destructors
Constructors
Destructor
Member
Initialization
Copy • Destructor is the ideal place to reset variables and release dynamically
Constructor
Unnamed
allocated memory and other resources.
Object
18
When and How to Use Destructors (cont.)
Constructors
Destructor
Member
Initialization
Copy else
Constructor
Buffer = NULL;
Unnamed }
Object
// Destructor : clears the buffer allocated in constructor
Static Members
~ MyString () {
Friends of cout << " Invoking destructor , clearing up" << endl;
Classes
if ( Buffer != NULL)
Workshop
delete [] Buffer ;
}
int GetLength () {
return strlen ( Buffer );
}
const char* GetString () {
return Buffer ;
}
}; // end of class MyString
int main () {
19
When and How to Use Destructors (cont.)
Constructors
Destructor
Member
Initialization
Workshop
20
Member Initialization
Initialization vs. Assignment
Constructors
Destructor
Member
Initialization
Unnamed
Object Initialization Assignment
Static Members int a = 2; a = 3;
Friends of double b(4.0); a = 4;
Classes
b = 2.0;
Workshop
b = 1.0;
22
Members Initialization
Constructors
Destructor
Member
Initialization
Unnamed
Object class CDate {
Static Members
private :
Friends of
int m_iDay , m_iMonth , m_iYear ;
Classes public :
Workshop CDate ();
CDate(int day , int month , int year):
m_iDay (day), m_iMonth (month), m_iYear (year)
{}
~CDate ();
...
};
23
Mandatory Members Initialization
Constructors
Destructor
Member
Initialization
Copy • References
Constructor
Unnamed
• Pointers
Object
• Const members
Static Members
Friends of
• Sub-objects which require arguments in constructors
Classes
24
Copy Constructor
Copy constructor
Constructors
Destructor
Member
Initialization
Copy
Constructor Concept 5
Unnamed A copy constructor is a special constructor that is called whenever a new object
Object
Static Members
is created and initialized with another object’s data.
Friends of
Classes • Default copy constructor: if there is no copy constructor, a default copy
Workshop constructor will be generated. Default copy constructor performs a bitwise
copy from the source to the current object (shallow copy).
• Our own copy constructor
26
When copies of objects are made
Constructors
Destructor
Member
Initialization
27
Shallow Copying and Associated Problems
Constructors
Destructor
Member
Initialization
Copy • When an object of the class MyString is copied, the pointer member is
Constructor
Unnamed
copied, but not the pointed buffer, resulting in two objects pointing to the
Object same dynamically allocated buffer in memory.
Static Members
28
Shallow Copying and Associated Problems (cont.)
Constructors
Destructor
Member
Initialization
Copy
Constructor
Unnamed
Object
Static Members
Friends of
Classes
Workshop
29
Deep Copy Using a Copy Constructor
Constructors
Destructor
Member
Initialization
Destructor
Member
Initialization
Copy
Constructor
Unnamed
Object
Static Members
Friends of
Classes
Workshop
31
Unnamed Object
Overview
Constructors
Destructor
Member
Initialization
Copy
Constructor
Concept 6
Unnamed An Unnamed object (anonymous object) is essentially an object that has no
Object
name
Static Members
Friends of
Classes class Wallet {
Workshop private :
int cents;
public :
Wallet (int cents): cents( cents ) {}
int getCents () { return cents; }
};
int main () {
Wallet momo (6); // normal object
Wallet (8); // unnamed object
}
33
Overview (cont.)
Constructors
Destructor
Member
Initialization
Copy • Because they have no name, there’s no way to refer to them beyond the
Constructor
Unnamed
point where they are created.
Object
• Consequently, they have “expression scope”, meaning they are created,
Static Members
evaluated, and destroyed all within a single expression.
Friends of
Classes • Returned object of a function is also considered as an unnamed object.
Workshop
34
Static Members
Instance and Static Members
Constructors
Destructor
Member
Initialization
Copy
Constructor Concept 7
Unnamed Each instance of a class has its own copies of the class’s instance variables.
Object
Static Members
• If a member variable is declared static, however, all instances of that class
Friends of have access to that variable.
Classes
Workshop
• If a member function is declared static, it may be called without any
instances of the class being defined.
36
Static Member Variables
Constructors
Destructor
Member
Initialization
Copy
Constructor Syntax
Unnamed static DataType VariableName;
Object
Static Members
• Even though static member variables are declared in a class, they are actually
Friends of
Classes defined outside the class declaration. The lifetime of a class’s static member
Workshop variable is the lifetime of the program. This means that a class’s static
member variables come into existence before any instances of the class are
created.
37
UML
Constructors
Destructor
Member
Initialization
Copy
Constructor
Name
Unnamed
Object
38
Listing 1
Constructors
Destructor
Member
Initialization
Destructor
Member
Initialization
Copy
Constructor
Unnamed
Object
Static Members
Friends of
Classes
Workshop
40
Static Member Functions
Constructors
Destructor
Member
Initialization
Copy
Constructor Syntax
Unnamed static ReturnType FunctionName (ParameterTypeList);
Object
Static Members
• A function that is a static member of a class cannot access any nonstatic
Friends of
Classes member data in its class.
Workshop
• A class’s static member functions can be called before any instances of the
class are created. This means that a class’s static member functions can
access the class’s static member variables before any instances of the class
are defined in memory. This gives you the ability to create very specialized
setup routines for class objects.
41
Listing 2
Constructors
Destructor
Member
Initialization
Destructor
Member
Initialization
Copy
Constructor Concept 8
Unnamed A friend is a function or class that is not a member of a class, but has access to
Object
Static Members
the private members of the class
Friends of
Classes • Friend functions or classes give a flexibility to the class.
Workshop
• It doesn’t violate the encapsulation of the class.
• Friendship is “directional”. It means if class A considers class B as its friend,
it doesn’t mean that class B considers A as a friend
Syntax
friend ReturnType FunctionName (ParameterTypeList)
friend class ClassName
44
UML
Constructors
Destructor
Member
Initialization
Copy
Constructor Container
Unnamed
Object
Static Members
«permit»
Friends of
Classes
Workshop
Iterator
45
Listing 3
Constructors
Destructor
Member
Initialization
Destructor
Member
Initialization
Copy
Constructor
1. What is the this pointer?
Unnamed
.........................................................................
Object .........................................................................
Static Members
.........................................................................
Friends of
Classes 2. When I create an instance of a class using new, where is the class created?
Workshop .........................................................................
.........................................................................
.........................................................................
48
Quiz (cont.)
Constructors
Destructor
Member
Initialization
Copy 3. My class has a raw pointer int* that contains a dynamically allocated array
of integers. Does sizeof report different sizes depending on the number of
Constructor
Unnamed
Object integers in the dynamic array?
Static Members .........................................................................
Friends of .........................................................................
Classes
Workshop
.........................................................................
4. All my class members are private, and my class does not contain any declared
friend class or function. Who can access these members?
.........................................................................
.........................................................................
.........................................................................
49
Quiz (cont.)
Constructors
Destructor
Member
Initialization
Unnamed
Object .........................................................................
Static Members .........................................................................
Friends of
Classes 6. What is a constructor good for?
Workshop .........................................................................
.........................................................................
.........................................................................
7. What is a destructor good for?
.........................................................................
.........................................................................
.........................................................................
50
Exercises
Constructors
Destructor
Member
Initialization
Unnamed
3. Car Class
Object 5. RetailItem Class
Static Members
• Programming Challenges of chapter 14 [Gaddis, 2014]
Friends of
Classes 1. Numbers Class
Workshop 2. Day of the Year
51
References
Deitel, P. (2016).
C++: How to program.
Pearson.
Gaddis, T. (2014).
Starting Out with C++ from Control Structures to Objects.
Addison-Wesley Professional, 8th edition.
Jones, B. (2014).
Sams teach yourself C++ in one hour a day.
Sams.