0% found this document useful (0 votes)
50 views20 pages

DBMS Chapter 5

Jjej

Uploaded by

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

DBMS Chapter 5

Jjej

Uploaded by

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

UNIT-3

3.1 Define Constructor and destructor:

Constructor: In C++, constructor is a special method which is invoked automatically at the


time of object creation. Generally it is used to initialize the data members of new object . The
constructor in C++ has the same name as class or structure name. Constructors are implicitly
called by the compiler. Once the object is created this constructor will be called.

Rules:

 Constructor name and class name should be same

 No return types for constructors not even void

 May or may not have arguments so it is possible for overloading

 All constructor functions should be declared in public area

Disadvantages:

 Never participates in inheritance

 Not able to find out the address of constructor and they will make implicit calls to
new and delete operators

Constructors can be defined inside or outside the class declaration:-

Syntax: /* defining a constructor within a class*/


<class-name>(list-of-parameters) {
// constructor definition
}
Syntax: /* defining the constructor outside the class*/
<class-name>::<class-name>(list-of-parameters){
// constructor definition
}
The prototype of Constructors is <class-name>(list-of-parameters);
Example:// defining the constructor within the class
#include <iostream>
using namespace std;
class Construct {
public: int a,b;
construct( ){
a=10;
b=20;}
};
int main(){
Construct s; // constructor gets called automatically when an object is created
Cout<<”a:”<<s.a<<”\t”<<”b:”<<s.b;
return 0;
}
Characteristics of constructors:
 The constructor has the same name as the class it belongs to.
 constructors are typically declared in the class's public section.
 Because constructors don't return values, they lack a return type.
 When we create a class object, the constructor is immediately invoked.
 Overloaded constructors are possible.
 Declaring a constructor virtual is not permitted.
 One cannot inherit a constructor.
 Constructor addresses cannot be referenced .
 When allocating memory, the constructor makes implicit calls to the new and delete
operators.

There can be two types of constructors in C++.

o Default constructor
o Parameterized constructor

Destructor: A destructor is also a special member function as a constructor. Destructor


destroys the class objects created by the constructor. Destructor has the same name as their
class name preceded by a tilde (~) symbol. It is not possible to define more than one
destructor. The destructor is only one way to destroy the object created by the constructor.
Hence destructor can-not be overloaded. Destructor neither requires any argument nor
returns any value. It is automatically called when the object goes out of scope. Destructors
release memory space occupied by the objects created by the constructor.
Syntax: ~ <class-name>() { }
Ex: ~item() { }
3.2 Explain parameterized Constructor:
A constructor which has parameters is called parameterized constructor. These parameters are
used to initialize an object hen it is created. It is used to provide different values to distinct
objects of the class.
syntax:
class classname{
Private: -----
-----
Public:
class name(arg list){
Code}};
/* example of C++ parameterized Constructor.*/
#include <iostream>
using namespace std;
class Test
{
public:
int x,y;
public:
Test(int a, int b) //parameterized constructor
{
cout<<"parameterized Constructor Invoked"<<endl;
x=a;
y=b;
}
Void display()
{
cout<<"x value"<<x<<endl;
cout<<"y value"<<y<<endl;
}
};
int main( )
{
Test t1(10,20);
t1.display();

}
Output:
Parameterized Constructor Invoked
X value:10
Y value:20
Example 2:/*initializing different value for distinct objects*/
#include <iostream>
using namespace std;
class Employee
{
public:
int id;
string name;
float salary;
Employee(int i, string n, float s)
{
id = i;
name = n;
salary = s;
}
void display()
{
cout<<id<<" "<<name<<" "<<salary<<endl;
}
};
Void main( ) {
Employee e1 (001, "red", 890000);
Employee e2=Employee(002, "black", 59000);
e1.display();
e2.display(); }
Output:
001 red 890000
002 black 59000

 Uses of Parameterized constructor:


1. It is used to initialize the various data elements of different objects with different
values when they are created.
2. It is used to overload constructors.

Default Constructor:A constructor which has no argument is known as default constructor. It


is invoked at the time of creating object. It has no parameters. It is also called a zero-
argument constructor.
/* example of C++ default Constructor.*/
#include <iostream>
using namespace std;
class Test
{
public:
int x,y;
public:
Test() //default constructor
{
cout<<"Default Constructor Invoked"<<endl;
cout<<”enter x and y values”<< endl;
cin>>x>>y; }
Void display(){
cout<<"x value"<<x<<endl;

cout<<"y value"<<y<<endl;}
};
Void main( ) {
Test t1;
t1.display(); }
Output:
Default Constructor Invoked
Enter x and y values:10 20

X value:10
Y value:20
3.3Describe multiple Constructors in a class:
Constructor overloading means having more than one constructor with the same
name. Constructors are methods invoked when an object is created. You have to use the same
name for all the constructors which is the class name. This is done by declaration the
constructor with a different number of arguments.
Ex:
class student{
Public:
int rollno;
string name;
student(){
rollno=0;
name=”null”;}
Student(int r,string sn){
rollno=r;
name=sn;
}
Void display(){
cout<<"rollno:"<<rollno<<endl;
cout<<"name:"<<name<<endl;}
};
void main()
{
student s1;
student s2(150,”red”);
s1.display();
s2.display();

}
Output:
rollno:0
name: null

rollno:150
name: red
3.4 Describe Constructors with default arguments:
A default argument is a value provided in a function declaration that is automatically
assigned by the compiler if the calling function doesn’t provide a value for the argument. In
case any value is passed, the default value is overridden.

#include<iostream>
using namespace std;
class Simple{
int data1;
int data2;
int data3;
public:
Simple(int a, int b=9, int c=8){
data1 = a;
data2 = b;
data3 = c;
}
void printData();
};
void Simple :: printData(){
cout<<"The value of data1, data2 and data3 is "<<data1<<", "<< data2<<" and "<<
data3<<endl;
}
int main(){
Simple s(12, 13);
s.printData();
return 0;
}
Output:
The value of data1, data2 and data3 is 12,13 and 8
3.5 Describe Copy Constructor:
A Copy constructor is a member function used to initializes an object using another object
of the same class.A Copy constructor is an overloaded constructor used to declare and
initialize an object from another object

 It takes a reference to an object of the same class as an argument.


 It is used in operator overloading.
 It is having class type parameters.

Copy Constructor is of two types:

o Default Copy constructor: The compiler defines the default copy constructor. If the
user defines no copy constructor, compiler supplies its constructor.
o User Defined constructor: The programmer defines the user-defined constructor.

Example: //copy constructor

#include <iostream>
using namespace std;
class Sample {
private:
double x, y;
public: Sample (double x, double y) {
(*this).x = x;
(*this). y = y; }
Sample(Sample &obj) //copy constructor
{
x=obj.x;
y=obj.y;}
void print( ){
cout<<”a:”<<a<<”b:”<<b;}
};
Void main( )
{
Sample s1(10,20);
Samaple s2(s1);
}
Characteristics of Copy Constructor:
1. The copy constructor is used to initialize the members of a newly created object by
copying the members of an already existing object.
2. Copy constructor takes a reference to an object of the same class as an argument.
Sample(Sample &t)
{
id=t.id;
}
3. The process of initializing members of an object through a copy constructor is known
as copy initialization.
4. It is also called member-wise initialization because the copy constructor initializes one
object with the existing object, both belonging to the same class on a member-by-member
copy basis.
Types of Copy Constructors

1. Default Copy Constructor

An implicitly defined copy constructor will copy the bases and members of an object in the
same order that a constructor would initialize the bases and members of the object.
Example: // Implicit copy constructor
#include<iostream>
using namespace std;
class Sample
{ int id;
public: void init(int x){
id=x; }
void display(){
cout<<endl<<"ID="<<id;}
};
int main(){
Sample obj1;
obj1.init(10);
obj1.display();
Sample obj2(obj1); //obj2=obj1;(implicit copy constructor calling)
obj2.display();
return 0;
}
2. User Defined Copy Constructor
A user-defined copy constructor is generally needed when an object owns pointers or non-
shareable references, such as to a file, in which case a destructor and an assignment
operator should also be written
// Explicitly copy constructor Calling
#include<iostream>
using namespace std;
class Sample
{
int id;
public:
void init(int x)
{
id=x;
}
Sample(){} //default constructor with empty body

Sample(Sample &t) //copy constructor


{
id=t.id;
}
void display()
{
cout<<endl<<"ID="<<id;
}
};
int main()
{
Sample obj1;
obj1.init(10);
obj1.display();
Sample obj2(obj1); //or obj2=obj1; copy constructor called
obj2.display();
return 0;
}
In C++, a Copy Constructor may be called in the following cases:
 When an object of the class is returned by value.
 When an object of the class is passed (to a function) by value as an argument.
 When an object is constructed based on another object of the same class.
 When the compiler generates a temporary object.
Dynamic Constructor:
When allocation of memory is done dynamically using dynamic memory
allocator new in a constructor, it is known as dynamic constructor. By using
this, we can dynamically initialize the objects.

Ex:
Class Sample{
Private: int size;
int *p;
public: Sample(int s){
size=s;
p=new int[size];}
~Sample(){
delete p;}
void getdata(){
cout<<”enter array elements”;
for(int i=0;i<size;i++)
cin>>p[i];}
Void display(){
cout<<”array elements are”;
for(int i=0;i<size;i++)
Cout<<p[i];}
};
Void main(){
Sample s1(5);
S1.getdata();
S1.display();
}

Multiple Constructors in a Class: Multiple constructors can be declared in a class. There


can be any number of constructors in a class.

class complex{
float real,img;
public:
complex( ) //default constructor
{
real=img=0;}
complex(float r) //single parameter parameterized constructor
{
real=img=r;}
complex(float r, float i) //two parameter parameterized constructor
{
real=r;img=i;}
complex(complex &c)//copy constructor
{
real=c.real; img=c.img;

}
complex sum(complex c ){
compl
ex t;
t.real=real+c.real;
t.img=img+c.img;
return t;}
void show(){
if(img>0)
cout<<real<<"+i"<<img<<endl;
else{
img=-img;
cout<<real<<"-i"<<img<<endl;
}
void main(){
complex c1(1,2);
complex c2(2,2);
compex c3;
c3=c1.sum(c3);
c3.show();}

Destructor:
A destructor is also a special member function as a constructor. Destructor destroys the
class objects created by the constructor. Destructor has the same name as their class name
preceded by a tilde (~) symbol. It is not possible to define more than one destructor. The
destructor is only one way to destroy the object created by the constructor. Hence
destructor can-not be overloaded. Destructor neither requires any argument nor returns any
value. It is automatically called when the object goes out of scope. Destructors release
memory space occupied by the objects created by the constructor.
Syntax: ~ <class-name>() { }
Ex: ~item() { }
Defining a destructor outside a class
<class-name>:: ~ <class-name>(){}
Characteristics:
 Like constructors destructors should be declared in public section only
 No return types not even void
 Destructor never takes arguments
 Class has only one destructor
 Destructor cannot be declared as static and const
Example:
/*constructor and destructor invoked*/
#include <iostream>
class Employee {
public: Employee( ) {
cout<<"Constructor Invoked"<<endl; }
~Employee( ) {
cout<<"Destructor Invoked"<<endl; }
};
int main( ) {
Employee e1;
Employee e2;
return 0; }

3.8Decribe Operator Overloading


In C++, we can overload: methods and constructors.

Types of overloading in C++ are:


o Function overloading
o Operator overloading

Function Overloading: Function Overloading is defined as the process of having two or more
function with the same name, but different in parameters is known as function overloading in
C++. In function overloading, the function is redefined by using either different types of
arguments or a different number of return types. The advantage of Function overloading is that
it increases the readability of the program because you don't need to use different names for
the same action.

// program of function overloading when number of arguments vary


#include <iostream>
class Cal {
public:
static int add(int a,int b){
return a + b;
}
static int add(int a, int b, int c) {
return a + b + c;
} };
int main( ) {
Cal C; // class object declaration.
cout<<C.add(10, 20)<<endl;
cout<<C.add(12, 20, 23);
return 0; }

Output:

30
55

// Program of function overloading with different types of arguments.


#include<iostream>
int mul(int,int);
float mul(float,int);
int mul(int a,int b) {
return a*b; }
float mul(double x, int y) {
return x*y; }
int main( ) {
int r1 = mul(6,7);
float r2 = mul(0.2,3);
std::cout << "r1 is : " <<r1<< std::endl;
std::cout <<"r2 is : " <<r2<< std::endl;
return 0; }
Output:
r1 is : 42
r2 is : 0.6
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. The advantage of Operators overloading is to perform
different operations on the same operand.
It is a mechanism in which we give an additional meaning to existing operators when they are
applied to user defined data types e.g. objects
 When an operator is overloaded, its original meanings are not lost
 Improves readability of code and increases scope of operator.

General rules of operator overloading-


 Only existing operators can be overloaded
 Overloaded operator must have at least one user defined operator
 Operator function cannot have default arguments
 All binary arithmetic overloaded operator functions explicitly return a value
 Precedence of operators cannot be altered. E.g. * has higher precedence over
+
syntax:
return_type class_name : : operator op(argument_list)
{
// body of the function.
}
 Can be overloaded either through non-static member function or friend
function
 Member function – takes no parameter. E.g. x.operator++()
 Friend function - takes one parameter. E.g. operator++(x)
 Increment(++) and decrement(--) have two versions, prefix and
postfix. To differentiate between them, a dummy parameter of type
int is used in postfix

// program to overload the unary operator ++.


// program to overload the unary operator ++using friend function.

Operator that cannot be overloaded are as follows:


o Scope operator (::)
o Sizeof
o member selector(.)
o member pointer selector(*)
o ternary operator(?:)
Binary Operator Overloading
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.
 Binary operator is an operator that requires two operands e.g. +,-,=
 Member function –
 Takes one parameter e.g. c.operator+(Circle x)
Syntax:
return_type :: operator binary_operator_symbol (arg)
{
// function definition
}
Ex:/* use binary (+) operator to add two complex numbers. */

#include <iostream>
class Complex_num
{
int x, y;
public:
void inp()
{
cout << " Input two complex number: " << endl;
cin >> x >> y;
}
// binary '+' operator to overload
Complex_num operator + (Complex_num obj)
{
Complex_num A;
A.x = x + obj.x;
A.y = y + obj.y;
return (A);
}
// overload the binary (-) operator
Complex_num operator - (Complex_num obj)
{
Complex_num A;
A.x = x - obj.x;
A.y = y - obj.y;
return (A);
}
void print() // display the result of addition {
cout << x << " + " << y << "i" << "\n";
}
void print2() // display the result of subtraction
{
cout << x << " - " << y << "i" << "\n";
} };
int main ()
{
Complex_num x1, y1, sum, sub;
x1.inp();
y1.inp();
sum = x1 + y1;
cout << "\n Entered values are: \n";
cout << " \t";
x1.print(); cout << " \t";
y1.print();
cout << "\n The addition of two complex (real and imaginary) numbers: ";
sum.print();
cout << "\n The subtraction of two complex (real and imaginary) numbers: ";
sub.print2();
return 0; }

You might also like