0% found this document useful (0 votes)
12 views23 pages

CMP1002 Lecture3

Lecture 3 discusses destructors and copy constructors in C++. A destructor, identified by a tilde (~) followed by the class name, is automatically invoked when an object is destroyed, while a copy constructor creates a new object as a copy of an existing one. The lecture also covers default memberwise assignment and provides examples of class implementations in C++.

Uploaded by

emironus.47
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views23 pages

CMP1002 Lecture3

Lecture 3 discusses destructors and copy constructors in C++. A destructor, identified by a tilde (~) followed by the class name, is automatically invoked when an object is destroyed, while a copy constructor creates a new object as a copy of an existing one. The lecture also covers default memberwise assignment and provides examples of class implementations in C++.

Uploaded by

emironus.47
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

CMP1002

LECTURE 3
ERKUT ARICAN
Destructor
Destructor
❑ Similar to a constructor, a destructor is a distinct category of a special member function.

❑ In a class, the destructor is identified by the tilde symbol (~) followed by the class name.
Destructor
❑ The rationale behind using the tilde symbol (~) followed by the class name as the naming
convention for destructors is that the tilde operator is the bitwise complement operator, and the
destructor can be thought of as the complement of the constructor, representing the reverse
operation to the constructor.
Destructor
❑ When an object is destroyed, the destructor of its class is automatically invoked without the
need for explicit invocation.

❑ This automatic invocation of a class's destructor happens, for instance, when a program exits
the scope in which an automatic object was instantiated, and that object is consequently
destroyed.

❑ The primary role of a destructor is not to release the memory occupied by an object, but to
perform necessary termination operations before the system recovers the memory, allowing it
to be reused for other objects.
Destructor
❑ In contrast to most functions, a destructor does not take any parameters or return any values.

❑ It is not permissible for a destructor to declare a return type, not even void, as opposed to
regular functions.

❑ A class is allowed to have only one destructor.

❑ Destructor overloading is not allowed.


Destructor
❖ Common Programming Error
❖ Any attempt to pass arguments to a destructor, define a return type (even void), return a value from a
destructor, or overload a destructor is considered a syntax error.
Destructor
❑ Even though destructors have not been provided for the classes presented so far, every class
has a default destructor

❑ If the programmer does not explicitly provide a destructor, the compiler creates an "empty"
destructor.
Destructor
// Header file for MyClass class
#ifndef MYCLASS_H
#define MYCLASS_H
class MyClass {
public:
// Constructor that takes an int value
MyClass(int value);
// Destructor
~MyClass();
private:
int value_;
};
#endif // MYCLASS_H
Destructor
// Implementation file for MyClass class
#include "MyClass.h"
#include <iostream>
// Constructor definition
MyClass::MyClass(int value)
: value_(value) {}
// Destructor definition
MyClass::~MyClass() {
std::cout << "Destructor called, value = " << value_ << std::endl;
}
Destructor
// Main file for MyClass example
#include "MyClass.h"
int main() {
// Create two instances of MyClass
MyClass obj1(10);
MyClass obj2(20);

return 0;
}
Copy
Constructor
Copy Constructor
❑ In C++ programming, a copy constructor is a distinctive type of constructor used to generate a
new object that is a copy of an existing object.

❑ A copy constructor takes its first argument as a reference to an object of the same type being
constructed, either as const or non-const. Additional parameters of any type may also be
present, all of which can have default values.
Copy Construtor
// Header file for Person class
#ifndef PERSON_H
#define PERSON_H
#include <string>
class Person {
public:
// Constructor
Person(const std::string& name, int age);
// Copy constructor
Person(const Person& other);
// Print function
void PrintInfo() const;
private:
std::string name_;
int age_;
};
#endif // PERSON_H
Copy Construtor
// Implementation file for Person class
#include "Person.h"
#include <iostream>
// Constructor definition
Person::Person(const std::string& name, int age)
: name_(name), age_(age) {}
// Copy constructor definition
Person::Person(const Person& other)
: name_(other.name_), age_(other.age_) {}
// Print function definition
void Person::PrintInfo() const {
std::cout << "Name: " << name_ << ", Age: " << age_ << std::endl;
}
Copy Construtor
// Main file for Person example
#include "Person.h"
int main() {
// Create a Person object and print its info
Person john("John Doe", 30);
john.PrintInfo();
// Create a copy of John and print its info
Person johnCopy(john);
johnCopy.PrintInfo();
return 0;
}
Default
Memberwise
Assignment
Default Memberwise Assignment
❑ In C++, the assignment operator (=) allows an object of a particular type to be assigned to
another object of the same type.

❑ The default behavior for such an assignment is to perform a memberwise assignment, where
each member of the object being assigned is copied into the corresponding member of the
target object.
Default Memberwise Assignment
// Header file for Person class
#ifndef PERSON_H
#define PERSON_H
#include <string>
class Person {
public:
// Constructor
Person(const std::string& name, int age);
// Copy constructor
Person(const Person& other);
// Default memberwise assignment operator
Person& operator=(const Person& other) = default;
// Print function
void PrintInfo() const;
private:
std::string name_;
int age_;
};
#endif // PERSON_H
Default Memberwise Assignment
// Implementation file for Person class
#include "Person.h"
#include <iostream>
// Constructor definition
Person::Person(const std::string& name, int age)
: name_(name), age_(age) {}
// Copy constructor definition
Person::Person(const Person& other)
: name_(other.name_), age_(other.age_) {}
// Print function definition
void Person::PrintInfo() const {
std::cout << "Name: " << name_ << ", Age: " << age_ << std::endl;
}
Default Memberwise Assignment
// Main file for Person example
#include "Person.h"
int main() {
// Create a Person object and print its info
Person john("John Doe", 30);
john.PrintInfo();
// Create a copy of John and print its info
Person johnCopy(john);
johnCopy.PrintInfo();
// Create another Person object and copy johnCopy into it using default memberwise assignment
Person jane("Jane Doe", 25);
jane = johnCopy;
jane.PrintInfo();
return 0;
}
In-class exercise
Write a C++ class named Person with the following private data members: name, age, and gender. In addition,
the class should also have the following public member functions:
•A default constructor that initializes the data members to empty strings or zero values.
•A parameterized constructor that takes three arguments and assigns them to the data members.
•A copy constructor that creates a deep copy of another Person object.
•A destructor that prints a message indicating which object is being destroyed.
•Getters and setters for each data member that perform input validation and error handling.
Use encapsulation to ensure that the data members are not directly accessible or modifiable by other classes or
functions.
Write a separate header, implementation, and main files for this class. In the main file, create two Person objects
using different constructors and display their information. Then, create a third Person object by copying one of
the existing objects and modifying its information using setters. Finally, display the information of all three
objects again and observe how the copy constructor and destructor work.
Thank You
End of lecture 3.

You might also like