0% found this document useful (0 votes)
7 views

Lect02 CPP More Class

The document discusses various aspects of classes in C++ including constructors, destructors, member initialization, copy constructors, static members, and friends of classes. Constructors are called when objects are created and can be used to initialize member variables, destructors are called when objects are destroyed to free resources.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Lect02 CPP More Class

The document discusses various aspects of classes in C++ including constructors, destructors, member initialization, copy constructors, static members, and friends of classes. Constructors are called when objects are created and can be used to initialize member variables, destructors are called when objects are destroyed to free resources.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 52

MORE ABOUT CLASSES

Bùi Tiến Lên

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

Constructor Activities Destructor

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

Copy • A constructor is a perfect place for us to initialize class member variables


Constructor

Unnamed
such as integers, pointers, and so on to known initial values
Object

Static Members # include <iostream >


Friends of
# include <string >
Classes using namespace std;
Workshop class Human {
private :
// Private member data:
string Name;
int Age;
public :
// constructor
Human () {
Age = 0;
}

7
When and How to Use Constructors (cont.)
Constructors

Destructor

Member
Initialization

Copy void SetName ( string HumansName ) {


Constructor
Name = HumansName ;
Unnamed }
Object
void SetAge (int HumansAge ) {
Static Members
Age = HumansAge ;
Friends of }
Classes
void IntroduceSelf () {
Workshop
cout << "I am " + Name << " and am ";
cout << Age << " years old" << endl;
}
};
int main () {
Human FirstMan ;
FirstMan . SetName ("Adam");
FirstMan . SetAge (30);
Human FirstWoman ;
FirstWoman . SetName ("Eve");

8
When and How to Use Constructors (cont.)
Constructors

Destructor

Member
Initialization

Copy FirstWoman . SetAge (28);


Constructor
FirstMan . IntroduceSelf ();
Unnamed FirstWoman . IntroduceSelf ();
Object
}
Static Members

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

Copy • As constructors can be overloaded just like functions, we can create a


Constructor

Unnamed
constructor that requires Human to be created with a name as a parameter,
Object for instance:
Static Members

Friends of class Human {


Classes public :
Workshop Human () {
// default constructor code here
}
Human( string HumansName ) {
// overloaded constructor code here
}
};
...
Human firstMan ;
Human firstWoman ("Eve");

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
...
};

• Advice: always define our own default constructor!

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

Copy • Destructor for Human class


Constructor

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

Static Members # include <iostream >


Friends of
using namespace std;
Classes

Workshop class MyString {


private :
char* Buffer ;
public :
// Constructor
MyString ( const char* InitialInput ) {
if( InitialInput != NULL) {
Buffer = new char [ strlen ( InitialInput ) + 1];
strcpy (Buffer , InitialInput );
}

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

Copy MyString SayHello (" Hello from String Class ");


Constructor
cout << " String buffer in MyString is " << SayHello . GetLength ();
Unnamed cout << " characters long" << endl;
Object
cout << " Buffer contains : ";
Static Members
cout << " Buffer contains : " << SayHello . GetString () << endl;
Friends of }
Classes

Workshop

20
Member Initialization
Initialization vs. Assignment
Constructors

Destructor

Member
Initialization

Copy • Distinguish between Assignment and Initialization


Constructor

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

Copy • This is members initialization


Constructor

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

Workshop class Human {


private :
Ancestor & ref; // reference member
Descendant * ptr; // pointer member
const int MAX; // const member
vector arr; // object member
public :
Human( Ancestor & r, Descendant *p) :
ref(r), ptr(p), MAX (100) , arr(MAX) {}
};

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

Copy • A variable is declared which is initialized from another object


Constructor

Unnamed Person p("Mickey"); // constructor


Object
Person r(p); // copy constructor
Static Members
Person q = p; // copy constructor
Friends of
Classes p = r; // assignment operator
Workshop • A value parameter is initialized from its corresponding argument.
doSomething(p); // copy constructor
• An object is returned by a function.
return p; // copy constructor

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

Friends of void UseMyString ( MyString Input) {


Classes
cout << " String buffer in MyString is " <<Input. GetLength ();
Workshop
cout << " characters long" << endl;
cout << " Buffer contains : " << Input. GetString () << endl;
}
int main () {
MyString SayHello (" Hello from String Class ");
// Pass SayHello as a parameter to the function
UseMyString ( SayHello );
return 0;
}

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

Copy • C++ requires that a copy constructor’s parameter be a reference object.


Constructor

Unnamed class MyString {


Object ...
Static Members // Copy constructor
Friends of MyString ( const MyString & CopySource ) {
Classes
if( CopySource . Buffer != NULL) {
Workshop
// ensure deep copy by first allocating own buffer
Buffer = new char [ strlen ( CopySource . Buffer ) + 1];
// copy from the source into local buffer
strcpy (Buffer , CopySource . Buffer );
}
else
Buffer = NULL;
}
...
}
30
Deep Copy Using a Copy Constructor (cont.)
Constructors

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

Wallet createWallet (int cents) {


return Wallet (cents);
}
...
cout << createWallet (5). getCents () << endl;

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

Static Members attribute1


Friends of
Classes attribute2 underline means static
Workshop
operation1()
operation2()

38
Listing 1
Constructors

Destructor

Member
Initialization

Copy # include <iostream >


Constructor
using namespace std;
Unnamed class Tree {
Object
private :
Static Members
static int objectCount ; // Static member variable .
Friends of
Classes
public :
// Constructor
Workshop
Tree () { objectCount ++; }
// Accessor function for objectCount
int getObjectCount () const { return objectCount ; }
};
// Definition written outside the class .
int Tree :: objectCount = 0;
int main () {
Tree oak , elm , pine;
cout << "We have " << pine. getObjectCount ()
<< " trees in our program !\n";
return 0;
} 39
Listing 1 (cont.)
Constructors

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

Copy # include <iostream >


Constructor
using namespace std;
Unnamed class Tree {
Object
private :
Static Members
static int objectCount ; // Static member variable .
Friends of
Classes
public :
// Constructor
Workshop
Tree () { objectCount ++; }
// Static function for objectCount
static int getObjectCount () { return objectCount ; }
};
// Definition written outside the class .
int Tree :: objectCount = 0;
int main () {
Tree oak , elm , pine;
cout << "We have " << Tree :: getObjectCount ()
<< " trees in our program !\n";
return 0;
} 42
Friends of Classes
Friends of Classes
Constructors

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

Copy class Human {


Constructor
private :
Unnamed string Name;
Object
int Age;
Static Members
friend void DisplayAge ( const Human& Person );
Friends of
Classes
public :
Human( string InputName , int InputAge ) {
Workshop
Name = InputName ;
Age = InputAge ;
}
};
void DisplayAge ( const Human& Person ) {
cout << Person .Age << endl;
}
int main () {
Human FirstMan ("Adam", 25);
DisplayAge ( FirstMan );
return 0;
} 46
Workshop
Quiz
Constructors

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

Copy 5. Can one class member method invoke another?


.........................................................................
Constructor

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

Copy • Programming Challenges of chapter 13 [Gaddis, 2014]


Constructor

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.

You might also like