0% found this document useful (0 votes)
17 views19 pages

Unit 3 - C++

Pdf

Uploaded by

bysggsggshsh
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)
17 views19 pages

Unit 3 - C++

Pdf

Uploaded by

bysggsggshsh
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/ 19

Object-oriented programming using C++

Unit III
Constructor And Destructor

❖ Introduction to constructor:
⚫ In C++, a constructor is a special member
function that is automatically called
when an object of a class is created.
⚫ It is used to initialize the object's data
members and perform any necessary
setup operations. Constructors have the
same name as the class and do not have
a return type, not even void.
⚫ Constructors can be overloaded, meaning
we can have multiple constructors with
different parameters. This allows for
flexibility in creating objects of the class.

Syntax:
class MyClass {
public:
// Constructor
MyClass() {
// Constructor code
}
};

◼ Characteristics of Constructor:
1. Same Name as Class:
⚫ Constructors have the same name as the class they belong to.
⚫ This is how the compiler identifies them as constructors.
2. No Return Type:
⚫ Unlike regular functions, constructors don't have a return type, not even void.
⚫ This is because constructors are automatically called when an object is created, and their
purpose is to initialize the object rather than return a value.
3. Automatic Invocation:
⚫ Constructors are automatically invoked when an object of the class is created.

By, Mritunjay Kr. Ranjan. & Shilpi Saxena, SOCSE -Sandip University, Nashik
Page 1 of 19
Object-oriented programming using C++
Unit III
Constructor And Destructor

⚫ They ensure that the object is properly initialized before it is used.


4. Initialization:
⚫ Constructors are primarily used to initialize the data members of the class.
⚫ This initialization can involve setting default values, assigning values based on
parameters passed to the constructor, or performing any necessary setup operations.
Program:
#include<iostream>
using namespace std;

//Creating a Class
class Construct
{
public:
//Creating a Constructor having same name as Class Name
Construct()
{
int a=10;
cout<<"Constructor Created The value of a is "<<a<<endl;
}
};
int main()
{
Construct con; //Creating a object of a class
//It will automatically call a Constructor
}
Output :
Constructor Created The value of a is 10

❖ Types of a constructor:

By, Mritunjay Kr. Ranjan. & Shilpi Saxena, SOCSE -Sandip University, Nashik
Page 2 of 19
Object-oriented programming using C++
Unit III
Constructor And Destructor

⚫ Mainly There are three types of Constructors in C++:


1. Default Constructor: Auto-generated if none specified. Initializes with defaults or leaves
uninitialized.
2. Parameterized Constructor: Takes parameters for custom initialization. Supports overloading.
3. Copy Constructor: Creates new object as copy of existing. Used during creation, function
arguments, or return by value. Compiler generates if not provided, performing shallow copy.
1. Default Constructor:
⚫ If we don't provide any constructors for our class, C++ automatically generates a default
constructor for us.
⚫ This constructor takes no arguments and initializes the data members with default values (if any).
⚫ If our class has no explicitly declared constructors and we don't provide a default value for all data
members, the default constructor will simply leave them uninitialized.
Syntax:
class DefCon {
public:
// Default constructor
DefCon() {
// Constructor code
}
};

Program:
#include <iostream>
using namespace std;

class DefCon {
public:
int num;
char character;

// Default constructor
DefCon() {
num = 0; // Default value for int
character = 'A'; // Default value for char
}
};

int main() {
DefCon obj;
cout << "num: " << obj.num << endl;

By, Mritunjay Kr. Ranjan. & Shilpi Saxena, SOCSE -Sandip University, Nashik
Page 3 of 19
Object-oriented programming using C++
Unit III
Constructor And Destructor

cout << "character: " << obj.character << endl;


return 0;
} Output :
num: 0
character: A
2. Parameterized Constructor:
⚫ This is a constructor that takes parameters.
⚫ It allows us to initialize the object with specific values when it is created.
⚫ We can have multiple parameterized constructors in a class, each taking different sets of
parameters.
⚫ This is known as constructor overloading.
Syntax:
class ParCons {
public:
// Parameterized constructor
ParCons(int num, char ch) {
// Constructor code to initialize data members
}
};

Program:
//*** Program to demonstrate Parameterized Construction **//
#include <iostream>
using namespace std;
class ParCons {
public:
int num;
char character;
Output :
num: 0
// Parameterized constructor
ParCons(int num, char ch) { character: A
num = num;
character = ch;
}
};

int main() {
ParCons obj(10, 'B');
cout << "num: " << obj.num << endl;
cout << "character: " << obj.character << endl;

By, Mritunjay Kr. Ranjan. & Shilpi Saxena, SOCSE -Sandip University, Nashik
Page 4 of 19
Object-oriented programming using C++
Unit III
Constructor And Destructor

return 0;
}

Program:
#include <iostream>
using namespace std;

class ParCons {
public:
int num;
char character;
float fnum;

// Parameterized constructor
ParCons(int n, char ch) {
num = n;
character = ch;
}

// Constructor Overloading
ParCons(int n, char ch, float f) {
num = n;
character = ch;
fnum = f;
}
};

int main() {
ParCons obj1(10, 'B');
ParCons obj2(20, 'C', 20.5);
Output :
cout << "num: " << obj1.num << endl; num: 10
cout << "character: " << obj1.character <<
character: B
endl << endl;

cout << "num: " << obj2.num << endl;


num: 20
cout << "character: " << obj2.character
<< endl; character: C
cout << "Float: " << obj2.fnum << endl;
Float: 20.5
return 0;
}

By, Mritunjay Kr. Ranjan. & Shilpi Saxena, SOCSE -Sandip University, Nashik
Page 5 of 19
Object-oriented programming using C++
Unit III
Constructor And Destructor

3. Copy Constructor:
⚫ A copy constructor is a special
constructor that initializes a new
object as a copy of an existing object.
⚫ It is invoked when a new object is
created from an existing object, either
by direct initialization, function
argument passing, or returning an
object by value.
⚫ If we don't provide a copy
constructor explicitly, the compiler
generates one for us, which performs
a shallow copy of the data members.
Syntax:
class CopyCons {
public:
// Copy constructor
CopyCons(const CopyCons& obj) {
// Constructor code to perform copy
}
};

Program:
#include <iostream>
using namespace std;

class CopyCons {
public:
int num;
char character;

CopyCons(int n, char ch) {


num = n;
character = ch;
}

// Copy constructor
CopyCons(const CopyCons& obj) {
num = obj.num;

By, Mritunjay Kr. Ranjan. & Shilpi Saxena, SOCSE -Sandip University, Nashik
Page 6 of 19
Object-oriented programming using C++
Unit III
Constructor And Destructor

character = obj.character;
} Output :
};
obj1 num: 10
int main() { obj1 character: B
CopyCons obj1(10, 'B');
CopyCons obj2 = obj1;
obj2 num: 10
cout << "obj1 num: " << obj1.num << endl;
cout << "obj1 character: " << obj1.character obj2 character: B
<< endl <<endl;

cout << "obj2 num: " << obj2.num << endl;


cout << "obj2 character: " << obj2.character << endl;
return 0;
}

❖ Destructors:
⚫ In C++, a destructor is a special member function that is automatically called when an object of a
class is destroyed or goes out of scope.
⚫ Its primary purpose is to perform cleanup operations such as releasing resources (like dynamic
memory allocation) or closing file handles that were acquired during the object's lifetime.
⚫ Destructors have the same name as the class preceded by a tilde (~) , and they do not take any
arguments.
◼ Use Cases for Destructors:
1. Resource Deallocation: Destructors are commonly used to release resources acquired
by the object during its lifetime, such as dynamic memory allocation, file handles,
database connections, etc.
2. Cleanup Operations: Destructors can perform cleanup operations necessary for the
proper functioning of the object, such as resetting internal states or closing open
connections.
3. Custom Logging and Debugging: Destructors can also be used for custom logging or
debugging purposes, allowing us to track the lifecycle of objects in our program.

Syntax:
class ClassName {
public:
// Constructor
ClassName() {

By, Mritunjay Kr. Ranjan. & Shilpi Saxena, SOCSE -Sandip University, Nashik
Page 7 of 19
Object-oriented programming using C++
Unit III
Constructor And Destructor

// Constructor code
}

// Destructor
~ClassName() {
// Destructor code
}
};

Program:
#include <iostream>
using namespace std;

class Resource {
public:
// Constructor
Resource() {
cout << "Resource acquired" << endl;
}

// Destructor Output :
~Resource() { Resource acquired
cout << "Resource released" << endl;
} Resource released
};

int main() {
// Creating an object of class Resource
Resource obj;

// Object goes out of scope, destructor is automatically called


return 0;
}

Program 2:
#include<iostream>
using namespace std;
class demo
{
int a=10,b=20;
public :
demo()
{
cout<<"Calling constructor"<<endl;
a=50;

By, Mritunjay Kr. Ranjan. & Shilpi Saxena, SOCSE -Sandip University, Nashik
Page 8 of 19
Object-oriented programming using C++
Unit III
Constructor And Destructor

b=70; Output :
} Calling constructor
void display() 50 , 70
{
50 , 70
cout<<a<<" , "<<b<<endl;
50 , 70
}
~demo() 50 , 70

{ constructor has been destroyed


cout<<"constructor has been
destroyed"<<endl;
}
};
int main()
{
demo d;
d.display();
d.display();
d.display();
d.display();
return 0;
}

❖ Difference between constructor and destructor:

Aspect Constructor Destructor


Definition Special member function of a Special member function of a class used to clean up
class used to initialize objects resources and perform finalization
Purpose Initialize the object's state and Release resources and perform cleanup tasks
data members
Syntax No return type, same name as No return type, same name as class, no explicit return
class, no explicit return statement
statement
Parameters Can have parameters for custom No parameters
initialization
Invocation Automatically invoked when an Automatically invoked when an object goes out of scope,
object is created or delete is called on a dynamically allocated object

Overloading Can be overloaded Cannot be overloaded


Multiple Only one constructor can be Only one destructor is called during object destruction
called during object creation
Memory Initializes memory for object Releases memory for object destruction
handling creation

By, Mritunjay Kr. Ranjan. & Shilpi Saxena, SOCSE -Sandip University, Nashik
Page 9 of 19
Object-oriented programming using C++
Unit III
Constructor And Destructor

Aspect Constructor Destructor


Inheritance Can be inherited and invoked in Destructors are automatically called in the reverse order of
derived classes through the constructor invocation in the constructor chain
constructor chain
Virtual Constructors cannot be virtual Destructors can be made virtual to ensure that the
appropriate destructor of the derived class is called when
deleting a base class pointer pointing to a derived class
object

❖ Order Of Constructors and Destructors in inheritance:

◼ Order of Constructors:
◆ Base Class Constructor:
⚫ When we create an object of a derived
class, the constructor of the base class
is called first.
⚫ This ensures that the base class
subobject is initialized before the
derived class subobject.
⚫ If the base class has its own base
classes, their constructors are called in
the same order as described here.
◆ Derived Class Constructor:
⚫ After the base class constructor is
executed, the constructor of the
derived class is called.
⚫ The derived class constructor
initializes the members specific to the
derived class.
◼ Order of Destructors:
◆ Derived Class Destructor:
⚫ When an object of a derived class goes out of scope or is explicitly destroyed, the destructor of the
derived class is called first.
⚫ This ensures that resources allocated by the derived class are deallocated before the resources
allocated by the base class.

By, Mritunjay Kr. Ranjan. & Shilpi Saxena, SOCSE -Sandip University, Nashik
Page 10 of
19
Object-oriented programming using C++
Unit III
Constructor And Destructor

◆ Base Class Destructor:


⚫ After the derived class destructor is executed, the destructor of the base class is called.
⚫ The base class destructor cleans up resources allocated by the base class.
Program :
#include <iostream>
using namespace std;

class A {
public:
A() {
cout << "A constructed" << endl;
}

~A() {
cout << "A destroyed" << endl;
}
};

class B {
public:
B() {
cout << "B constructed" << endl;
}

~B() {
cout << "B destroyed" << endl;
}
};

class C {
public:
C() {
cout << "C constructed" << endl;
}

~C() {
cout << "C destroyed" << endl;
}
};

int main() {
cout << "Creating object for Class C..." << endl;
C c; // Create object of class C
cout << "Creating object for Class A..." << endl;
A a; // Create object of class A

By, Mritunjay Kr. Ranjan. & Shilpi Saxena, SOCSE -Sandip University, Nashik
Page 11 of
19
Object-oriented programming using C++
Unit III
Constructor And Destructor

cout << "Creating object for Class B..." << endl;


B b; // Create object of class B
cout << "Exiting main function..." << endl;
return 0;
}

Output :
Creating object for Class C...
C constructed
Creating object for Class A...
A constructed
Creating object for Class B...
B constructed
Exiting main function...
B destroyed
A destroyed
C destroyed

❖ Dynamic memory allocation:


⚫ Dynamic memory allocation in C++
refers to the process of allocating memory
for variables at runtime rather than
compile time.
⚫ This allows we to allocate memory for
variables whose size or quantity is not
known until the program runs.
⚫ In C++, the new and delete operators
are used for dynamic memory allocation
and deallocation, respectively.
⚫ It allows programmers to allocate and
deallocates memory during runtime,
providing flexibility in memory
management.
1. new Operator:

By, Mritunjay Kr. Ranjan. & Shilpi Saxena, SOCSE -Sandip University, Nashik
Page 12 of
19
Object-oriented programming using C++
Unit III
Constructor And Destructor

⚫ It dynamically allocates memory for a single object of the specified data type on the heap.
⚫ Returns a pointer to the allocated memory.
2. delete Operator:
⚫ Deallocates memory previously allocated using new.
⚫ Prevents memory leaks by releasing dynamically allocated memory.
Syntax:
type *pointer_name = new type;

delete pointer_variable;

Program:
#include <iostream>
using namespace std;

int main() {
// Dynamically allocate memory for a single integer
int *ptr = new int;

// Assign a value to the dynamically allocated integer


*ptr = 10;

// Print the value


cout << "Dynamically allocated integer: " << *ptr << endl;

// Deallocate memory
delete ptr;
Output :
return 0; Dynamically allocated integer: 10
}

❖ Operator Overloading in C++:


⚫ in C++, Operator overloading is a compile-time polymorphism.
⚫ It is an idea of giving special meaning to an existing operator in C++ without changing its
original meaning.
⚫ In C++, we can change the way operators work for user-defined types like objects and structures.
This is known as operator overloading.
⚫ For example, suppose we have created three objects c1, c2 and result from a class named Complex
that represents complex numbers.

By, Mritunjay Kr. Ranjan. & Shilpi Saxena, SOCSE -Sandip University, Nashik
Page 13 of
19
Object-oriented programming using C++
Unit III
Constructor And Destructor

⚫ Since operator overloading allows us to change how operators work, we can redefine how the +
operator works and use it to add the complex numbers of c1 and c2
Syntax:
class className {
... .. ...
public
returnType operator symbol (arguments) {
... .. ...
}
... .. ...
};

Where :
➢ returnType is the return type of the function.
➢ operator is a keyword.
➢ symbol is the operator we want to overload. Like: +, <, -, ++, etc.
➢ arguments is the arguments passed to the function.

◼ Types of a operators in C++:


⚫ Operators in C++ can be categorized into several types based on their functionality, usage, and
arity (number of operands they operate on).
⚫ Here's an overview of the main types of operators in C++:
◆ Unary Operators:
⚫ Unary operators operate on a single operand
⚫ They are essential for overloading operators that perform operations on a single
operand, such as increment (++) and decrement (--).
⚫ These operators can be overloaded as member functions or non-member functions.
◆ Binary Operators:
⚫ Binary operators operate on two operands.
⚫ They are commonly overloaded to define operations between two objects of a class
or between an object of a class and another type.
⚫ Binary operators can be overloaded as member functions or non-member functions.
◆ Ternary Operator:
⚫ The ternary operator (? :) is the only ternary operator in C++.
⚫ It takes three operands and is used for conditional expressions.

By, Mritunjay Kr. Ranjan. & Shilpi Saxena, SOCSE -Sandip University, Nashik
Page 14 of
19
Object-oriented programming using C++
Unit III
Constructor And Destructor

⚫ Although it's less commonly overloaded compared to unary and binary operators, it can
still be overloaded if necessary.
⚫ However, its overloading syntax is not as straightforward as unary and binary operators.

Unary Binary Ternary


1. Unary plus (+) 1. Addition (+) Conditional operator (ternary)
(?)
2. Unary minus (-) 2. Subtraction (-)
3. Increment (++) 3. Multiplication (*)
4. Decrement (--) 4. Division (/)
5. Dereference (*) 5. Modulus (%)
6. Address-of (&) 6. Assignment (=)
7. Logical NOT (!) 7. Equality (==)
8. Bitwise NOT (~) 8. Inequality (!=)
9. Size of (sizeof) 9. Less than (<)
10. Type information (typeid) 10. Greater than (>)
11. Dynamic memory allocation (new) 11. Less than or equal to (<=)
12. Dynamic memory deallocation 12. Greater than or equal to
(delete) (>=)
13. Logical AND (&&)
14. Logical OR ( || )
15. Bitwise AND (&)
16. Bitwise OR ( | )
17. Bitwise XOR (^)
18. Left shift (<<)
19. Right shift (>>)

◼ Unary Operator Overloading:

By, Mritunjay Kr. Ranjan. & Shilpi Saxena, SOCSE -Sandip University, Nashik
Page 15 of
19
Object-oriented programming using C++
Unit III
Constructor And Destructor

⚫ Unary operator overloading in C++ involves defining custom behavior for unary
operators (operators that operate on a single operand) when they are used with objects of
user-defined classes.
⚫ This allows us to extend the functionality of our classes and provide intuitive syntax for
operations.
Program:
#include<iostream>
using namespace std;

class Unary {
int a, b, c;

public :
// Constructor to initialize object with values of a, b, and c
Unary(int x, int y, int z) {
a = x;
b = y;
c = z;
cout << a << " " << b << " " << c << endl;
}

// Overloaded unary negation (-) operator


Unary operator -() {
// Create a new object with negated values of a, b, and c and print them
Unary(-a, -b, -c);
}
// Overloaded unary plus (+) operator
Unary operator +() {
// Create a new object with original values of a, b, and c and print them
Unary(+a, +b, +c);
}
};

int main() {
cout << "\n Original Values: " << endl;

// Create an object u of class Unary with values (10, -20, 30) and print them
Unary u(10, -20, 30);

cout << "Using - overloaded operator: " << endl;

// Apply unary negation (-) operator to object u, create new object u2 with
negated values
Unary u2 = -u;

By, Mritunjay Kr. Ranjan. & Shilpi Saxena, SOCSE -Sandip University, Nashik
Page 16 of
19
Object-oriented programming using C++
Unit III
Constructor And Destructor

cout << "Using + overloaded operator: " << endl;

// Apply unary plus (+) operator to object u, create new object u3 with
original values
Unary u3 = +u;

return 0;
}

Output :
Original Values:
10 -20 30
Using - overloaded operator:
-10 20 -30
Using + overloaded operator:
10 -20 30

◼ Binary Operator Overloading


⚫ Binary operator overloading in C++ refers to the process of defining custom behavior for
binary operators (operators that operate on two operands) when they are used with objects
of user-defined classes.
⚫ This allows us to extend the functionality of our classes and provide intuitive syntax for
operations.
◆ Importance of Binary Operator Overloading:
⚫ Binary operator overloading is essential in C++ for several reasons:
1. Expressive Syntax: Operator overloading allows us to write code that
resembles natural mathematical expressions, making our code more intuitive
and expressive.
2. Customization: By overloading operators, we can define custom behavior
for operators when they are used with objects of our classes. This gives us
flexibility in how we design and use our classes.

By, Mritunjay Kr. Ranjan. & Shilpi Saxena, SOCSE -Sandip University, Nashik
Page 17 of
19
Object-oriented programming using C++
Unit III
Constructor And Destructor

3. Consistency: Overloading operators allows us to maintain consistency in


our code by providing the same semantics for built-in and user-defined
types.
4. Code Readability: Overloaded operators can enhance the readability of our
code by providing clear and concise syntax for operations on custom types.
Program:
#include <iostream>
using namespace std;

class Complex {
private:
double real;
double imag;

public:
// Constructor
Complex(double r, double i) {
real = r;
imag = i;
}

// Binary operator overloading for addition


Complex operator+(const Complex& other) const {
return Complex(real + other.real, imag + other.imag);
}

// Method to display the complex number


void display() const {
cout << "Real: " << real << ", Imaginary: " << imag << endl;
}
};

int main() {
// Create two complex numbers
Complex c1(2.5, 3.5);
Complex c2(1.5, 2.5);

// Add two complex numbers using overloaded operator


Complex result = c1 + c2;

// Display the result


result.display();

By, Mritunjay Kr. Ranjan. & Shilpi Saxena, SOCSE -Sandip University, Nashik
Page 18 of
19
Object-oriented programming using C++
Unit III
Constructor And Destructor

Output :
return 0;
} Real: 4, Imaginary: 6

******************

Reference: The contents present in the notes have also been taken from WWW (world
wide Web resources) and compiled in the notes.

Note: Students are advised to read the notes carefully and build the concept. And practice
in the perspective approach.

***********************

By, Mritunjay Kr. Ranjan. & Shilpi Saxena, SOCSE -Sandip University, Nashik
Page 19 of
19

You might also like