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

C++ Constructors and Destructors Explained

This document provides an overview of constructors and destructors in C++, detailing their characteristics, types, and differences. It explains various types of constructors such as default, parameterized, copy, private, and discusses the concept of constructor overloading. Additionally, it covers static data members and functions, as well as function and operator overloading in C++.

Uploaded by

Niharikaa
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)
80 views23 pages

C++ Constructors and Destructors Explained

This document provides an overview of constructors and destructors in C++, detailing their characteristics, types, and differences. It explains various types of constructors such as default, parameterized, copy, private, and discusses the concept of constructor overloading. Additionally, it covers static data members and functions, as well as function and operator overloading in C++.

Uploaded by

Niharikaa
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

UNIT – 2

Constructor and Destructorin C++


CONSTRUCTOR:

A class constructor is a special member function of a class that is


executed whenever we create new objects of that class.
 Constructors can be very useful for setting initial values for certain
member variables.
Characteristics of Constructors
 Constructors essentially have the same name as the class name.
 For constructors, there is no return type.
 When an object is created, the constructor is automatically invoked.
 Constructors are always placed in the class's public scope.
 The default constructor is created automatically if the constructor is not
created.
 The constructor name declaration is case-sensitive.
 A constructor is not implicitly inherited.
Uses
The 'calling part' is performed automatically whenever a new Object of the class
is created. Constructors can be used for efficient memory management, which is
not possible with functions. Destructor can be used to destroy
the constructors when not needed.
Syntax:
Class classname
public:
class Name()
{
//set fields and call methods
}

Example
Class bca
{
Bca ()
{
Cout << “Welcome;
}
};
Void main()
{
Bca b; // Constructor will call Automatically
}
A constructor is different from normal functions in the following ways:
 The constructor has the same name as the class itself
 Constructors don’t have a return type
 A constructor is automatically called when an object is created.
A constructor can be defined either inside or outside of the class definition. To
declare it outside the class, we can use the scope resolution operator, like:

TYPES OF CONSTRUCTOR:

There are 3 types of constructors available, they are:

Default Constructor.
Default Constructors: Default constructor is the constructor which doesn't
take any argument. It has no parameters. .
Default constructor for a class as a constructor that can be called with no
arguments (this includes a constructor whose parameters all have default
arguments)
Syntax:
constructor_name ( ) ; // Declaration
class_name :: class_name ( ) //Defination
{
------ // Body of the constructor
}
Example Program
#include <iostream>
using namespace std;
class Employee
{
public:
Employee()
{
cout<<"Constructor Invoked"<<endl;
}
~Employee()
{
cout<<"Destructor Invoked"<<endl;
}
};
int main(void)
{
Employee e1; //creating an object of Employee
Employee e2; //creating an object of Employee
return 0;
}
Note: Even if we do not define any constructor explicitly, the compiler will
automatically provide a default constructor implicitly.

Parameterized constructor
A constructor with parameters is known as a parameterized constructor. This
is the preferred method to initialize member data.
An object is declared in a parameterized constructor, the initial values have
to be passed as arguments to the constructor function. The normal way of object
declaration may not work. The constructors can be called explicitly or implicitly.
Syntax
constructor_name (int x, int y ) ; // Declaration
class_name :: class_name (int x, int y ) //Defination
{
------ // Body of the constructor
}
Example program
#include <iostream>
using namespace std;
class Employee {
public:
int id;//data member (also instance variable)
string name;//data member(also instance variable)
float salary;
Employee(int i, string n, float s)
{
id = i;
name = n;
salary = s;
}
void display()
{
cout<<id<<" "<<name<<" "<<salary<<endl;
}
};
int main(void) {
Employee e1(101, "Sonoo", 890000);
// (or)Employee e1 =Employee(101, "Sonoo", 890000);
Employee e2(102, "Nakul", 59000);
//(or) Employee e2=Employee(102, "Nakul", 59000);
[Link]();
[Link]();
return 0;
}
Copy Constructor
Generally in a constructor the object of its own class can’t be passed as a
value parameter. But the class's own object can be passed as a reference parameter.
Such constructor having reference to the object of its own class is known as
copy constructor. It creates a new object as a copy of an existing object.
Syntax

class class_name{
public:
class_name(class_name & obj)
{
// obj is same class another object
// Copy Constructor code
}
//... other Variables & Functions
}
Example

#include<iostream>
using namespace std;

class Point
{
private:
int x, y;
public:
Point(int x1, int y1) { x = x1; y = y1; }

// Copy constructor
Point(const Point &p2) {x = p2.x; y = p2.y; }

int getX() { return x; }


int getY() { return y; }
};

int main()
{
Point p1(10, 15); // Normal constructor is called here
Point p2 = p1; // Copy constructor is called here

// Let us access values assigned by constructors


cout << "p1.x = " << [Link]() << ", p1.y = " <<
[Link]();
cout << "\np2.x = " << [Link]() << ", p2.y = " <<
[Link]();

return 0;
}
private constructor
A private constructor is a special type of constructor that can only be accessed
within the same class in which it is declared. It is used to restrict the instantiation
of a class to just within its own implementation.
For example, consider a class named "Singleton" that is meant to be a singleton
class, i.e., there can only be one instance of the class at a time. This can be
achieved by declaring the constructor as private:
class Singleton
{
private:
Singleton() {};
static Singleton *instance;

public:
static Singleton *getInstance()
{
if (!instance)
{
instance = new Singleton();
}
return instance;
}
};
In this example, the constructor is declared as private, making it inaccessible from
outside the class. To create an instance of the class, the static getInstance method is
used, which returns a pointer to the single instance of the class. The static variable
instance is used to store the single instance of the class, and is initialized to NULL
when the program starts.

Static constructor :
A static constructor in C++ is not a thing. C++ does not have a static constructor as
a language construct. However, you can achieve similar behavior by declaring a
static method that is called at the start of the program before the main method is
executed.
Here's an example of a static method being used to initialize some static variables
in a class:
class Example
{
private:
static int count;

public:
static void initialize()
{
count = 0;
}

int getCount()
{
return count;
}

void incrementCount()
{
count++;
}
};

int Example::count = 0;

int main()
{
Example::initialize();

Example ex1;
[Link]();

Example ex2;
[Link]();

cout << [Link]() << endl; // Outputs 2


cout << [Link]() << endl; // Outputs 2

return 0;
}
In this example, the initialize method is declared as static, which means that it can
be called on the class itself, without having to create an instance of the class. The
static variable count is also declared and initialized in the class. In the main
method, the initialize method is called before any instances of the class are created,
ensuring that the static variable is properly initialized.
Destructor

A destructor is a member function with the same name as its class prefixed
by a ~ (tilde).
A destructor is a special method called automatically during the destruction
of an object. Actions executed in the destructor include the following: Recovering
the heap space allocated during the lifetime of an object.
Basically Constructor is used to initialize the objects (at the time of
creation), and they are automatically invoked. This saves us from the garbage
values assigned to data members; during initializing.
Syntax:
Class class_name
{
public:
~class_name() //Destructor
{
}
}:
Example
Class bca
{
public:
~bca() //Destructor
{
}
}:

Difference between Constructor and Destructor in C++ :

S.
Constructor Destructor
No.
Constructor helps to initialize the object of Whereas destructor is used to
1.
a class. destroy the instances.
It is declared as className( arguments if Whereas it is declared as ~
2.
any ){Constructor’s Body }. className( no arguments ){ }.
Constructor can either accept arguments or
3. While it can’t have any arguments.
not.
A constructor is called when an instance or It is called while object of the
4.
object of a class is created. class is freed or deleted.
5. Constructor is used to allocate the memory While it is used to deallocate the
S.
Constructor Destructor
No.
to an instance or object. memory of an object of a class.
6. Constructor can be overloaded. While it can’t be overloaded.
Here, its name is also same as the
The constructor’s name is same as the
7. class name preceded by the tiled
class name.
(~) operator.
In a class, there can be multiple While in a class, there is always a
8.
constructors. single destructor.
There is a concept of copy constructor
While here, there is no copy
9. which is used to initialize an object from
destructor concept.
another object.
They are often called in reverse
order of constructor.
10. They are often called in successive order.

Constructor overloading
Overloaded constructors essentially have the same name (name of the class)
and different number of arguments.
 A constructor is called depending upon the number and type of arguments
passed.
 While creating the object, arguments must be passed to let compiler know,
which constructor needs to be called.
The constructor must follow one or both of the two rules below.

 All the constructors in the class should have a different number of


parameters.
 It is also allowed in a class to have constructors with the same number of
parameters and different data types.

Examples of Legal and Illegal Constructor Overloading


Here are some examples of legal and illegal constructor overloading:

 Addition(int x, int y) and Addition(double x, double y) is legal in constructor


overloading.
 Addition(int x, int y) and Addition(int x, double y) is legal in constructor
overloading.
 Addition(int x, int y) and Addition(int x, int y) is illegal in constructor
overloading.
 Addition(double x, double y) and Addition(double x, double y) is illegal in
constructor overloading.
 Addition(int x, int y) and Addition(int x, int y, int z) is legal in
constructor overloading.
// Constructor overloading
#include <iostream>
using namespace std;

class construct
{

public:
float area;

// Constructor with no parameters


construct()
{
area = 0;
}

// Constructor with two parameters


construct(int a, int b)
{
area = a * b;
}

void disp()
{
cout<< area<< endl;
}
};

int main()
{
// Constructor Overloading
// with two different constructors
// of class name
construct o;
construct o2( 10, 20);

[Link]();
[Link]();
return 1;
}
Advantages of Constructor Overloading
 It acts as compile-time polymorphism.
 Including more constructors in a class allows the flexibility of creating
various types of objects in a class.
 Helpful while solving complex problems since it makes the constructor's
name easier to remember if several constructors have the same name

Static Data Member


Static data members are class members that are declared using static keywords.
A static data member has certain special characteristics. They are:-

 It is initialized to zero when the first object of its class is created. No other
initialization is permitted.
 Only one copy of that member is created for the entire class and is shared by
all the objects of that class, no matter how many objects are created.
 It is visible only within the class, but its lifetime is the entire program.

A static variable is normally used to maintain a value common to the entire class.
For e.g, to hold the count of objects created. Note that the type and scope of each
static member variable must be declared outside the class definition. This is
necessary because the static data members are stored separately rather than as a
part of an object.
Declaration
syntax:
static data_type member_name;

Defining the static data member:

It should be defined outside of the class following this syntax:


data_type class_name :: member_name =value;

If you are calling a static data member within a member function, member function
should be declared as static (i.e. a static member function can access the static
data members)

Let’s see a simple example

#include <iostream>
using namespace std;
class Demo
{
public:
static int ABC;
};

//defining
int Demo :: ABC =10;

int main()
{

cout<<"\nValue of ABC: "<<Demo::ABC;


return 0;
}

Output

Value of ABC: 10

Static Member Function


like a static member variable, we can also have static member functions. A
member function that is declared static has the following properties:-

 A static function can have access to only other static members (function or
variable) declared in the same class.

 A static member function can be called using the class name (instead of
its object) as follows-Class_name::Function_name()

Consider the example, here static data member is accessing through the static
member function:
#include <iostream>
using namespace std;class Demo
{
private:
static int X; public:
static void fun()
{
cout <<"Value of X: " << X << endl;
}
};//defining
int Demo :: X =10;
int main()
{
Demo X; [Link]();

return 0;
}

Output
Value of X: 10

C++ Overloading
If we create two or more members having the same name but different in number
or type of parameter, it is known as C++ overloading.

Types of overloading in C++ are:


 Function overloading
 Operator overloading

Function /Method Overloading


FUNCTION OVERLOADING
Function overloading is a feature in C++ where two or more functions can
have the same name but different parameters. Function overloading can be
considered as an example of polymorphism feature in C++
Two or more functions having same name but different argument(s) are
known as overloaded functions.
Rules

 The same function name is used for more than one function definition
 The functions must differ either by the arity or types of their parameters
Types
 Different number of parameter
 Different types of parameter
 Different parameter with different return values

Example : Different number of parameter


Class aaa
Sum(int a, Int b) // same function name & different parameter
{
}
Sum(int x, int y, int z)
{
}
Example Program
#include <iostream>
class Addition
{
public:
int sum(int num1,int num2) // Two argument
{
return num1+num2;
}
int sum(int num1,int num2, int num3) // Three argument
{
return num1+num2+num3;
}
};
int main(void)
{
Addition obj;
cout<<[Link](20, 15);
cout<<[Link](81, 100, 10);
return 0;
}
Example : Different Types of parameter
Class aaa
Sum(int a, int b) // same function name & different parameter
{
}
Sum(float x,int z)
{
}
Example Program
#include <iostream>
class Addition
{
public:
int sum(int num1,int num2) // Both arguments are integer
{
return num1+num2;
}
float sum(float num3,int num4) // one float , one integer
{
return num3+num4;
}
};
int main(void)
{
Addition obj;
cout<<[Link](20, 15);
cout<<[Link](81.50, 100);
return 0;
}
Different parameter with different return values
Example
Class aaa
Int Sum(int a, Int b) // Integer return type
{
}
Float Sum(float x, int y) // Float return type
{
}
Example program
#include <iostream>
class Add
{
public:
int sum(int num1,int num2) // Integer return type
{
return num1+num2;
}
float sum(float num3,int num4) // Float return type

{
return num3+num4;
}
};
int main(void)
{
Addition obj;
cout<<[Link](20, 15);
cout<<[Link](81.50, 100);
return 0;
}

Operator Overloading
we can change the way operators work for user-defined types like objects
and structures. This is known as operator overloading
Operator overloading is a compile-time polymorphism in which the operator
is overloaded to provide the special meaning to the user-defined data type.
Operator overloading is used to overload or redefine most of the operators
available in C++. It is used to perform the operation on the user-defined data type.
For example, C++ provides the ability to add the variables of the user-defined data
type that is applied to the built-in data types.
Operator that cannot be overloaded are as follows:

 Scope operator (::)


 Sizeof
 member selector(.)
 member pointer selector(*)
 ternary operator(?:)

Syntax of Operator Overloading

class inside the operator definition


return_type operator symbol()
{
//body of the function
}
class outside the operator definition
return_type class_name : : operator op(argument_list)
{
// body of the function.
}
Rules for Operator Overloading
 Existing operators can only be overloaded, but the new operators cannot be
overloaded.
 The overloaded operator contains at least one operand of the user-defined
data type.
 We cannot use friend function to overload certain operators. However, the
member function can be used to overload those operators.
 When unary operators are overloaded through a member function take no
explicit arguments, but, if they are overloaded by a friend function, takes one
argument.
 When binary operators are overloaded through a member function takes one
explicit argument, and if they are overloaded through a friend function takes
two explicit arguments.

Types of Operator overloading

 Unary Operator overloading


 Binary Operator overloading

Unary operator overloading


The unary operators operate on a single operand and following are the examples of
Unary operators −
The increment (++) and decrement (--) operators.
 The unary minus (-) operator.
 The logical not (!) operator
Syntax
Return_Type classname :: operator op(Argument list)
{
Function Body
}
Example Program
#include <iostream>
using namespace std;
class Test
{
private:
int num;
public:
Test(): num(8){}
void operator ++() {
num = num+2;
}
void Print() {
cout<<"The Count is: "<<num;
}
};
int main()
{
Test tt;
++tt; // calling of a function "void operator ++()"
[Link]();
return 0;
}
Binary Operator Overloading
Binary Operator Overloading in the C++ programming language. An operator
which contains two operands to perform a mathematical operation is called the
Binary Operator Overloading. It is a polymorphic compile technique where a
single operator can perform various functionalities by taking two operands from
the programmer or user. There are multiple binary operators like +, -, *, /, etc., that
can directly manipulate or overload the object of a class.
Example Program
#include <iostream>
using namespace std;
class A
{

int x;
public:
A(){}
A(int i)
{
x=i;
}
void operator+(A);
void display();
};
void A :: operator+(A a)
{

int m = x+a.x;
cout<<"The result of the addition of two objects is : "<<m;

}
int main()
{
A a1(5);
A a2(4);
a1+a2;
return 0;
}

You might also like