EEE100 Lecture 8 - Classes and Object
EEE100 Lecture 8 - Classes and Object
Declaring a Class
Syntax:
Example:
5
Instantiating an Object
Objects are created from a class using the class name.
Example:
6
Accessing Members
• Dot operator (.): Used for objects.
• Arrow operator (->): Used for pointers to objects.
Example:
7
Accessing Members
• Dot operator (.): Used for objects.
• Arrow operator (->): Used for pointers to objects.
Example:
8
Example:
9
Constructors
Special member functions called when an object is created.
Default Constructor:
Constructor Overloading:
10
Constructors
Special member functions called when an object is created.
Default Constructor:
Parameterized Constructor:
Constructor Overloading:
11
Destructor
Called when an object is destroyed (e.g., goes out of scope).
Example:
12
Copy Constructor
A copy constructor initializes an object by copying another
object.
Example:
13
Copy Constructor
Shallow vs. Deep Copy:
▪ Shallow copying can lead to multiple objects pointing to the
same memory, causing issues on deletion.
Example:
14
Copy Constructor
Shallow vs. Deep Copy:
▪ A deep copy ensures each object has its own copy of
dynamically allocated memory.
Example:
15
Example:
16
this Pointer
The this pointer refers to the current object.
Example:
17
friend Keyword
Allows external functions/classes to access private members.
Example:
19
Summary
• Classes encapsulate data and behavior.
• Constructors initialize objects; destructors clean up.
• Copy/move constructors manage object copying efficiently.
• public/private enforce encapsulation.
• this refers to the current object.
• struct and class differ in default access.
END