SlideShare a Scribd company logo
1 of 34
Download to read offline
Constructor and Destructor

Arrays, Pointers, References, and the Dynamic Allocation
Operators
H S Rana
Center For information Technology
UPES Dehradun, India

October 3, 2012

H S Rana (UPES)

Constructor and Destructor

October 3, 2012

1 / 23
Constructor and Destructor

Array Of Object

Example
The syntax for declaring and
using anobject array is exactly
the same as it is for any other
type of array.
class cl {
int i;
public:
void set_i(int j) { i=j; }
int get_i() { return i; }
};

H S Rana (UPES)

Constructor and Destructor

October 3, 2012

2 / 23
Constructor and Destructor

Array Of Object

Example
The syntax for declaring and
using anobject array is exactly
the same as it is for any other
type of array.
class cl {
int i;
public:
void set_i(int j) { i=j; }
int get_i() { return i; }
};

H S Rana (UPES)

int main()
{
cl ob[3];
int i;
for(i=0; i<3; i++)
ob[i].set_i(i+1);
for(i=0; i<3; i++)
cout << ob[i].get_i()<< "n";
return 0;
}

Constructor and Destructor

October 3, 2012

2 / 23
Constructor and Destructor

Array Of Object

Example
Parameterized Constructor can
be used to initialize each
object in array
class cl {
int i;
public:
cl(int j) { i=j; } // constructor
int get_i() { return i; }
};

H S Rana (UPES)

Constructor and Destructor

October 3, 2012

3 / 23
Constructor and Destructor

Array Of Object

Example
int main()
{
cl ob[3] = {1, 2, 3}; // initializers
//Equal to cl ob[3] = { cl(1), cl(2), cl(3) };
int i;
for(i=0; i<3; i++)
cout << ob[i].get_i() << "n";
return 0;
}

H S Rana (UPES)

Constructor and Destructor

October 3, 2012

4 / 23
Constructor and Destructor

Array Of Object

Example
If an object’s constructor requires two or more arguments
class cl {
int h;
int i;
public:
cl(int j, int k) { h=j; i=k; } // constructor with 2 paramet
int get_i() {return i;}
int get_h() {return h;}
};

H S Rana (UPES)

Constructor and Destructor

October 3, 2012

5 / 23
Constructor and Destructor

Array Of Object
Example
int main()
{
cl ob[3] = {
cl(1, 2), // initialize
cl(3, 4),
cl(5, 6)
};
int i;
for(i=0; i<3; i++) {
cout << ob[i].get_h();
cout << ", ";
cout << ob[i].get_i() << "n";
}
return 0;
}
H S Rana (UPES)

Constructor and Destructor

October 3, 2012

6 / 23
Constructor and Destructor

Creating Initialized vs. Uninitialized Arrays
If you want to create uninitialized array
Example
class cl {
int i;
public:
cl(int j) { i=j; }
int get_i() { return i; }
};

H S Rana (UPES)

Constructor and Destructor

October 3, 2012

7 / 23
Constructor and Destructor

Creating Initialized vs. Uninitialized Arrays
If you want to create uninitialized array
Example
class cl {
int i;
public:
cl(int j) { i=j; }
int get_i() { return i; }
};

main function
main()
{
cl a[9]; // error,
}
H S Rana (UPES)

Constructor and Destructor

October 3, 2012

7 / 23
Constructor and Destructor

Pointer to Object
We can define pointers to objects. When accessing members of a class given a
pointer to an object, use the arrow operator instead of the dot operator.
Example
class cl {
int i;
public:
cl(int j) { i=j; }
int get_i() { return i; }
};
int main()
{
cl ob(88), *p;
p = &ob; // get address of ob
cout << p->get_i(); // use -> to call get_i()
return 0;
}
H S Rana (UPES)

Constructor and Destructor

October 3, 2012

8 / 23
Constructor and Destructor

Pointer to Object
when a pointer is incremented, it points to the next element of its type. For
example, an integer pointer will point to the next integer.
Example
class cl {
int i;
public:
cl() { i=0; }
cl(int j) { i=j; }
int get_i() { return i;}};
int main(){
cl ob[3] = {1, 2, 3}
cl *p;
int i;
p = ob; // get start of array
for(i=0; i<3; i++) {
cout << p->get_i() << "n";
p++; // point to next object }
H S Rana (UPES) 0;}
Constructor and Destructor
return

October 3, 2012

9 / 23
Constructor and Destructor

The this Pointer
When a member function is called, it is automatically passed an implicit argument
that is a pointer to the invoking object (that is, the object on which the function
is called). This pointer is called this.
Example
class pwr {
double b;
int e;
double val;
public:
pwr(double base, int exp);
double get_pwr() { return val; }
};

H S Rana (UPES)

Constructor and Destructor

October 3, 2012

10 / 23
Constructor and Destructor

The this Pointer
Example
pwr::pwr(double base, int exp)
{b = base;
e = exp;
val = 1;
if(exp==0) return;
for( ; exp>0; exp--) val = val * b;}

H S Rana (UPES)

Constructor and Destructor

October 3, 2012

11 / 23
Constructor and Destructor

The this Pointer
Example
pwr::pwr(double base, int exp)
{b = base;
e = exp;
val = 1;
if(exp==0) return;
for( ; exp>0; exp--) val = val * b;}
Another Definition
pwr::pwr(double base, int exp)
{ this->b = base;
this->e = exp;
this->val = 1;
if(exp==0) return;
for( ; exp>0; exp--)
this->val = this->val * this->b;
}
H S Rana (UPES)

Constructor and Destructor

October 3, 2012

11 / 23
Constructor and Destructor

The this Pointer

main function
int main()
{
pwr x(4.0, 2), y(2.5, 1), z(5.7, 0);
cout << x.get_pwr() << " ";
cout << y.get_pwr() << " ";
cout << z.get_pwr() << "n";
return 0;
}

H S Rana (UPES)

Constructor and Destructor

October 3, 2012

12 / 23
Constructor and Destructor

Dynamics Allocation of Memory
Memory Allocation operators
C++ provides two dynamic allocation operators: new and delete. These
operators are used to allocate and free memory at run time.The new operator
allocates memory and returns a pointer to the start of it. The delete operator
frees memory previously allocated using new

H S Rana (UPES)

Constructor and Destructor

October 3, 2012

13 / 23
Constructor and Destructor

Dynamics Allocation of Memory
Memory Allocation operators
C++ provides two dynamic allocation operators: new and delete. These
operators are used to allocate and free memory at run time.The new operator
allocates memory and returns a pointer to the start of it. The delete operator
frees memory previously allocated using new
General form
The general forms of new and delete are :
p_var = new type;
delete p_var;
Here, p_var is a pointer variable that receives a pointer to
memory that is large enough to hold an item of type type.
H S Rana (UPES)

Constructor and Destructor

October 3, 2012

13 / 23
Constructor and Destructor

Dynamics Allocation of Memory
Example
#include <iostream>
#include <new>
using namespace std;
int main()
{
int *p;
try {
p = new int; // allocate space for an int
} catch (bad_alloc xa) {
cout << "Allocation Failuren";
return 1;
}
*p = 100;
cout << "At " << p << " ";
cout << "is the value " << *p << "n";
delete p;
return (UPES)
H S Rana 0;
Constructor and Destructor

October 3, 2012

14 / 23
Constructor and Destructor

Initializing Allocated Memory

We can initialize allocated memory to some known value by putting an initializer
after the type name in the new statement.

H S Rana (UPES)

Constructor and Destructor

October 3, 2012

15 / 23
Constructor and Destructor

Initializing Allocated Memory

We can initialize allocated memory to some known value by putting an initializer
after the type name in the new statement.
General form
p_var = new var_type (initializer);

H S Rana (UPES)

Constructor and Destructor

October 3, 2012

15 / 23
Constructor and Destructor

Initializing Allocated Memory
Example
#include <iostream>
#include <new>
using namespace std;
int main()
{
int *p;
try {
p = new int (87); // initialize to 87
} catch (bad_alloc xa) {
cout << "Allocation Failuren";
return 1;
}
cout << "At " << p << " ";
cout << "is the value " << *p << "n";
delete p;
return 0;
} H S Rana (UPES)
Constructor and Destructor

October 3, 2012

16 / 23
Constructor and Destructor

Allocating Arrays

We can allocate arrays using new operator.

H S Rana (UPES)

Constructor and Destructor

October 3, 2012

17 / 23
Constructor and Destructor

Allocating Arrays

We can allocate arrays using new operator.
General form
p_var = new array_type [size];
size specifies the number of elements in the array.
To free an array, use delete
delete [ ] p_var;

H S Rana (UPES)

Constructor and Destructor

October 3, 2012

17 / 23
Constructor and Destructor

Allocating Arrays
Example
#include <iostream>
#include <new>
using namespace std;
int main()
{
int *p, i;
try {
p = new int [10]; // allocate 10 integer array
} catch (bad_alloc xa) {
cout << "Allocation Failuren";
return 1;
}
for(i=0; i<10; i++ )
p[i] = i;
for(i=0; i<10; i++)
cout << p[i] << " ";
delete (UPES) p; // releaseConstructor array
the and Destructor
H S Rana []
October 3, 2012

18 / 23
Constructor and Destructor

Allocating Objects
We can allocate object using new operator.When we do this, an object is created
and a pointer is returned to it.

H S Rana (UPES)

Constructor and Destructor

October 3, 2012

19 / 23
Constructor and Destructor

Allocating Objects
We can allocate object using new operator.When we do this, an object is created
and a pointer is returned to it.
Example
#include <iostream>
#include <new>
#include <cstring>
using namespace std;
class balance {
double cur_bal;
char name[80];
public:
void set(double n, char *s) {
cur_bal = n;
strcpy(name, s);}
void get_bal(double &n, char *s) {
n = cur_bal;
strcpy(s, name);}};
H S Rana (UPES)

Constructor and Destructor

October 3, 2012

19 / 23
Constructor and Destructor

Allocating Objects

H S Rana (UPES)

Constructor and Destructor

October 3, 2012

20 / 23
Constructor and Destructor

Allocating Objects
Example
int main(){
balance *p; char s[80];
double n;
try {
p = new balance;
} catch (bad_alloc xa) {
cout << "Allocation Failuren";
return 1;}
p->set(12387.87, "Rahul Kumar");
p->get_bal(n, s);
cout << s << "’s balance is: " << n;
cout << "n";
delete p;
return 0;}
H S Rana (UPES)

Constructor and Destructor

October 3, 2012

20 / 23
Constructor and Destructor

Allocating Objects
dynamically allocated objects may have constructors and destructors

H S Rana (UPES)

Constructor and Destructor

October 3, 2012

21 / 23
Constructor and Destructor

Allocating Objects
dynamically allocated objects may have constructors and destructors
Example
class balance {
double cur_bal;
char name[80];
public:
balance(double n, char *s) {
cur_bal = n;
strcpy(name, s);
}
~balance() {
cout << "Destructing ";
cout << name << "n";
}
void get_bal(double &n, char *s) {
n = cur_bal;
strcpy(s, name);}
H S Rana (UPES)
Constructor and Destructor
};

October 3, 2012

21 / 23
Constructor and Destructor

Allocating Objects

H S Rana (UPES)

Constructor and Destructor

October 3, 2012

22 / 23
Constructor and Destructor

Allocating Objects
Example
int main()
{
balance *p;
char s[80];
double n;
// this version uses an initializer
try {
p = new balance (12387.87, "Rahul Kumar");
} catch (bad_alloc xa) {
cout << "Allocation Failuren";
return 1;
}
p->get_bal(n, s);
cout << s << "’s balance is: " << n;
cout << "n";
delete p;
returnH S0; (UPES)
Rana
Constructor and Destructor

October 3, 2012

22 / 23
Constructor and Destructor

Const Argument

An argument of a function can be declared as const.

H S Rana (UPES)

Constructor and Destructor

October 3, 2012

23 / 23
Constructor and Destructor

Const Argument

An argument of a function can be declared as const.
Example
int strlrn(const char *p)
int length(const String &s)
The qualifier const tell the compiler that the function should not modify the
argument. Compiler will generate the error when this condition is violated.

H S Rana (UPES)

Constructor and Destructor

October 3, 2012

23 / 23

More Related Content

What's hot

C++11 smart pointer
C++11 smart pointerC++11 smart pointer
C++11 smart pointer
Lei Yu
 
FP 201 - Unit4 Part 2
FP 201 - Unit4 Part 2FP 201 - Unit4 Part 2
FP 201 - Unit4 Part 2
rohassanie
 

What's hot (20)

Module 02 Pointers in C
Module 02 Pointers in CModule 02 Pointers in C
Module 02 Pointers in C
 
Lecture 9
Lecture 9Lecture 9
Lecture 9
 
Memory Management C++ (Peeling operator new() and delete())
Memory Management C++ (Peeling operator new() and delete())Memory Management C++ (Peeling operator new() and delete())
Memory Management C++ (Peeling operator new() and delete())
 
detailed information about Pointers in c language
detailed information about Pointers in c languagedetailed information about Pointers in c language
detailed information about Pointers in c language
 
Pointers in C
Pointers in CPointers in C
Pointers in C
 
L7 pointers
L7 pointersL7 pointers
L7 pointers
 
Data structure week 2
Data structure week 2Data structure week 2
Data structure week 2
 
What's New in C++ 11/14?
What's New in C++ 11/14?What's New in C++ 11/14?
What's New in C++ 11/14?
 
Pointers [compatibility mode]
Pointers [compatibility mode]Pointers [compatibility mode]
Pointers [compatibility mode]
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocation
 
C pointers and references
C pointers and referencesC pointers and references
C pointers and references
 
Dynamic Memory Allocation(DMA)
Dynamic Memory Allocation(DMA)Dynamic Memory Allocation(DMA)
Dynamic Memory Allocation(DMA)
 
C++11 smart pointer
C++11 smart pointerC++11 smart pointer
C++11 smart pointer
 
Arrry structure Stacks in data structure
Arrry structure Stacks  in data structureArrry structure Stacks  in data structure
Arrry structure Stacks in data structure
 
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and ...
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and ...Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and ...
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and ...
 
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 5 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 5 of 5 by...Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 5 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 5 of 5 by...
 
Chp4(ref dynamic)
Chp4(ref dynamic)Chp4(ref dynamic)
Chp4(ref dynamic)
 
OpenGL 4.6 Reference Guide
OpenGL 4.6 Reference GuideOpenGL 4.6 Reference Guide
OpenGL 4.6 Reference Guide
 
glTF 2.0 Reference Guide
glTF 2.0 Reference GuideglTF 2.0 Reference Guide
glTF 2.0 Reference Guide
 
FP 201 - Unit4 Part 2
FP 201 - Unit4 Part 2FP 201 - Unit4 Part 2
FP 201 - Unit4 Part 2
 

Viewers also liked

Oop lec 5-(class objects, constructor & destructor)
Oop lec 5-(class objects, constructor & destructor)Oop lec 5-(class objects, constructor & destructor)
Oop lec 5-(class objects, constructor & destructor)
Asfand Hassan
 

Viewers also liked (17)

Oop lec 5-(class objects, constructor & destructor)
Oop lec 5-(class objects, constructor & destructor)Oop lec 5-(class objects, constructor & destructor)
Oop lec 5-(class objects, constructor & destructor)
 
Inheritance in OOPS
Inheritance in OOPSInheritance in OOPS
Inheritance in OOPS
 
Ashish oot
Ashish ootAshish oot
Ashish oot
 
Constructor and Destructor PPT
Constructor and Destructor PPTConstructor and Destructor PPT
Constructor and Destructor PPT
 
Constructor & destructor
Constructor & destructorConstructor & destructor
Constructor & destructor
 
Constructor & destructor
Constructor & destructorConstructor & destructor
Constructor & destructor
 
Oop concepts
Oop conceptsOop concepts
Oop concepts
 
01 introduction to oop and java
01 introduction to oop and java01 introduction to oop and java
01 introduction to oop and java
 
Inheritance
InheritanceInheritance
Inheritance
 
Object Oriented Programming in Python
Object Oriented Programming in PythonObject Oriented Programming in Python
Object Oriented Programming in Python
 
Inheritance
InheritanceInheritance
Inheritance
 
Inheritance in oops
Inheritance in oopsInheritance in oops
Inheritance in oops
 
Object Oriented Programming Using C++
Object Oriented Programming Using C++Object Oriented Programming Using C++
Object Oriented Programming Using C++
 
Constructors and Destructors
Constructors and DestructorsConstructors and Destructors
Constructors and Destructors
 
Constructors & destructors
Constructors & destructorsConstructors & destructors
Constructors & destructors
 
constructor and destructor-object oriented programming
constructor and destructor-object oriented programmingconstructor and destructor-object oriented programming
constructor and destructor-object oriented programming
 
Constructor & Destructor
Constructor & DestructorConstructor & Destructor
Constructor & Destructor
 

Similar to Dynamics allocation

CONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptx
CONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptxCONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptx
CONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptx
DeepasCSE
 
2.overview of c++ ________lecture2
2.overview of c++  ________lecture22.overview of c++  ________lecture2
2.overview of c++ ________lecture2
Warui Maina
 
18 dec pointers and scope resolution operator
18 dec pointers and scope resolution operator18 dec pointers and scope resolution operator
18 dec pointers and scope resolution operator
SAFFI Ud Din Ahmad
 

Similar to Dynamics allocation (20)

OOP-Lecture-05 (Constructor_Destructor).pptx
OOP-Lecture-05 (Constructor_Destructor).pptxOOP-Lecture-05 (Constructor_Destructor).pptx
OOP-Lecture-05 (Constructor_Destructor).pptx
 
CONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptx
CONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptxCONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptx
CONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptx
 
Constructors and Destructors
Constructors and DestructorsConstructors and Destructors
Constructors and Destructors
 
Lk module5 pointers
Lk module5 pointersLk module5 pointers
Lk module5 pointers
 
Presentation
PresentationPresentation
Presentation
 
Constructors & Destructors [Compatibility Mode].pdf
Constructors & Destructors [Compatibility Mode].pdfConstructors & Destructors [Compatibility Mode].pdf
Constructors & Destructors [Compatibility Mode].pdf
 
Constructor and Destructors in C++
Constructor and Destructors in C++Constructor and Destructors in C++
Constructor and Destructors in C++
 
Constructor ppt
Constructor pptConstructor ppt
Constructor ppt
 
Constructors and destructors in C++
Constructors and destructors in  C++Constructors and destructors in  C++
Constructors and destructors in C++
 
Pointers
PointersPointers
Pointers
 
P1
P1P1
P1
 
Object Oriented Programming using C++ Part I
Object Oriented Programming using C++ Part IObject Oriented Programming using C++ Part I
Object Oriented Programming using C++ Part I
 
2.overview of c++ ________lecture2
2.overview of c++  ________lecture22.overview of c++  ________lecture2
2.overview of c++ ________lecture2
 
Go OO! - Real-life Design Patterns in PHP 5
Go OO! - Real-life Design Patterns in PHP 5Go OO! - Real-life Design Patterns in PHP 5
Go OO! - Real-life Design Patterns in PHP 5
 
18 dec pointers and scope resolution operator
18 dec pointers and scope resolution operator18 dec pointers and scope resolution operator
18 dec pointers and scope resolution operator
 
Concept of constructors
Concept of constructorsConcept of constructors
Concept of constructors
 
array of objects slides.pdf
array of objects slides.pdfarray of objects slides.pdf
array of objects slides.pdf
 
Structures
StructuresStructures
Structures
 
Getters_And_Setters.pptx
Getters_And_Setters.pptxGetters_And_Setters.pptx
Getters_And_Setters.pptx
 
Op ps
Op psOp ps
Op ps
 

More from Kumar

More from Kumar (20)

Graphics devices
Graphics devicesGraphics devices
Graphics devices
 
Fill area algorithms
Fill area algorithmsFill area algorithms
Fill area algorithms
 
region-filling
region-fillingregion-filling
region-filling
 
Bresenham derivation
Bresenham derivationBresenham derivation
Bresenham derivation
 
Bresenham circles and polygons derication
Bresenham circles and polygons dericationBresenham circles and polygons derication
Bresenham circles and polygons derication
 
Introductionto xslt
Introductionto xsltIntroductionto xslt
Introductionto xslt
 
Extracting data from xml
Extracting data from xmlExtracting data from xml
Extracting data from xml
 
Xml basics
Xml basicsXml basics
Xml basics
 
XML Schema
XML SchemaXML Schema
XML Schema
 
Publishing xml
Publishing xmlPublishing xml
Publishing xml
 
DTD
DTDDTD
DTD
 
Applying xml
Applying xmlApplying xml
Applying xml
 
Introduction to XML
Introduction to XMLIntroduction to XML
Introduction to XML
 
How to deploy a j2ee application
How to deploy a j2ee applicationHow to deploy a j2ee application
How to deploy a j2ee application
 
JNDI, JMS, JPA, XML
JNDI, JMS, JPA, XMLJNDI, JMS, JPA, XML
JNDI, JMS, JPA, XML
 
EJB Fundmentals
EJB FundmentalsEJB Fundmentals
EJB Fundmentals
 
JSP and struts programming
JSP and struts programmingJSP and struts programming
JSP and struts programming
 
java servlet and servlet programming
java servlet and servlet programmingjava servlet and servlet programming
java servlet and servlet programming
 
Introduction to JDBC and JDBC Drivers
Introduction to JDBC and JDBC DriversIntroduction to JDBC and JDBC Drivers
Introduction to JDBC and JDBC Drivers
 
Introduction to J2EE
Introduction to J2EEIntroduction to J2EE
Introduction to J2EE
 

Recently uploaded

Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
KarakKing
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
heathfieldcps1
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
QucHHunhnh
 

Recently uploaded (20)

Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptx
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptx
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxSKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
 
Dyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptxDyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptx
 

Dynamics allocation

  • 1. Constructor and Destructor Arrays, Pointers, References, and the Dynamic Allocation Operators H S Rana Center For information Technology UPES Dehradun, India October 3, 2012 H S Rana (UPES) Constructor and Destructor October 3, 2012 1 / 23
  • 2. Constructor and Destructor Array Of Object Example The syntax for declaring and using anobject array is exactly the same as it is for any other type of array. class cl { int i; public: void set_i(int j) { i=j; } int get_i() { return i; } }; H S Rana (UPES) Constructor and Destructor October 3, 2012 2 / 23
  • 3. Constructor and Destructor Array Of Object Example The syntax for declaring and using anobject array is exactly the same as it is for any other type of array. class cl { int i; public: void set_i(int j) { i=j; } int get_i() { return i; } }; H S Rana (UPES) int main() { cl ob[3]; int i; for(i=0; i<3; i++) ob[i].set_i(i+1); for(i=0; i<3; i++) cout << ob[i].get_i()<< "n"; return 0; } Constructor and Destructor October 3, 2012 2 / 23
  • 4. Constructor and Destructor Array Of Object Example Parameterized Constructor can be used to initialize each object in array class cl { int i; public: cl(int j) { i=j; } // constructor int get_i() { return i; } }; H S Rana (UPES) Constructor and Destructor October 3, 2012 3 / 23
  • 5. Constructor and Destructor Array Of Object Example int main() { cl ob[3] = {1, 2, 3}; // initializers //Equal to cl ob[3] = { cl(1), cl(2), cl(3) }; int i; for(i=0; i<3; i++) cout << ob[i].get_i() << "n"; return 0; } H S Rana (UPES) Constructor and Destructor October 3, 2012 4 / 23
  • 6. Constructor and Destructor Array Of Object Example If an object’s constructor requires two or more arguments class cl { int h; int i; public: cl(int j, int k) { h=j; i=k; } // constructor with 2 paramet int get_i() {return i;} int get_h() {return h;} }; H S Rana (UPES) Constructor and Destructor October 3, 2012 5 / 23
  • 7. Constructor and Destructor Array Of Object Example int main() { cl ob[3] = { cl(1, 2), // initialize cl(3, 4), cl(5, 6) }; int i; for(i=0; i<3; i++) { cout << ob[i].get_h(); cout << ", "; cout << ob[i].get_i() << "n"; } return 0; } H S Rana (UPES) Constructor and Destructor October 3, 2012 6 / 23
  • 8. Constructor and Destructor Creating Initialized vs. Uninitialized Arrays If you want to create uninitialized array Example class cl { int i; public: cl(int j) { i=j; } int get_i() { return i; } }; H S Rana (UPES) Constructor and Destructor October 3, 2012 7 / 23
  • 9. Constructor and Destructor Creating Initialized vs. Uninitialized Arrays If you want to create uninitialized array Example class cl { int i; public: cl(int j) { i=j; } int get_i() { return i; } }; main function main() { cl a[9]; // error, } H S Rana (UPES) Constructor and Destructor October 3, 2012 7 / 23
  • 10. Constructor and Destructor Pointer to Object We can define pointers to objects. When accessing members of a class given a pointer to an object, use the arrow operator instead of the dot operator. Example class cl { int i; public: cl(int j) { i=j; } int get_i() { return i; } }; int main() { cl ob(88), *p; p = &ob; // get address of ob cout << p->get_i(); // use -> to call get_i() return 0; } H S Rana (UPES) Constructor and Destructor October 3, 2012 8 / 23
  • 11. Constructor and Destructor Pointer to Object when a pointer is incremented, it points to the next element of its type. For example, an integer pointer will point to the next integer. Example class cl { int i; public: cl() { i=0; } cl(int j) { i=j; } int get_i() { return i;}}; int main(){ cl ob[3] = {1, 2, 3} cl *p; int i; p = ob; // get start of array for(i=0; i<3; i++) { cout << p->get_i() << "n"; p++; // point to next object } H S Rana (UPES) 0;} Constructor and Destructor return October 3, 2012 9 / 23
  • 12. Constructor and Destructor The this Pointer When a member function is called, it is automatically passed an implicit argument that is a pointer to the invoking object (that is, the object on which the function is called). This pointer is called this. Example class pwr { double b; int e; double val; public: pwr(double base, int exp); double get_pwr() { return val; } }; H S Rana (UPES) Constructor and Destructor October 3, 2012 10 / 23
  • 13. Constructor and Destructor The this Pointer Example pwr::pwr(double base, int exp) {b = base; e = exp; val = 1; if(exp==0) return; for( ; exp>0; exp--) val = val * b;} H S Rana (UPES) Constructor and Destructor October 3, 2012 11 / 23
  • 14. Constructor and Destructor The this Pointer Example pwr::pwr(double base, int exp) {b = base; e = exp; val = 1; if(exp==0) return; for( ; exp>0; exp--) val = val * b;} Another Definition pwr::pwr(double base, int exp) { this->b = base; this->e = exp; this->val = 1; if(exp==0) return; for( ; exp>0; exp--) this->val = this->val * this->b; } H S Rana (UPES) Constructor and Destructor October 3, 2012 11 / 23
  • 15. Constructor and Destructor The this Pointer main function int main() { pwr x(4.0, 2), y(2.5, 1), z(5.7, 0); cout << x.get_pwr() << " "; cout << y.get_pwr() << " "; cout << z.get_pwr() << "n"; return 0; } H S Rana (UPES) Constructor and Destructor October 3, 2012 12 / 23
  • 16. Constructor and Destructor Dynamics Allocation of Memory Memory Allocation operators C++ provides two dynamic allocation operators: new and delete. These operators are used to allocate and free memory at run time.The new operator allocates memory and returns a pointer to the start of it. The delete operator frees memory previously allocated using new H S Rana (UPES) Constructor and Destructor October 3, 2012 13 / 23
  • 17. Constructor and Destructor Dynamics Allocation of Memory Memory Allocation operators C++ provides two dynamic allocation operators: new and delete. These operators are used to allocate and free memory at run time.The new operator allocates memory and returns a pointer to the start of it. The delete operator frees memory previously allocated using new General form The general forms of new and delete are : p_var = new type; delete p_var; Here, p_var is a pointer variable that receives a pointer to memory that is large enough to hold an item of type type. H S Rana (UPES) Constructor and Destructor October 3, 2012 13 / 23
  • 18. Constructor and Destructor Dynamics Allocation of Memory Example #include <iostream> #include <new> using namespace std; int main() { int *p; try { p = new int; // allocate space for an int } catch (bad_alloc xa) { cout << "Allocation Failuren"; return 1; } *p = 100; cout << "At " << p << " "; cout << "is the value " << *p << "n"; delete p; return (UPES) H S Rana 0; Constructor and Destructor October 3, 2012 14 / 23
  • 19. Constructor and Destructor Initializing Allocated Memory We can initialize allocated memory to some known value by putting an initializer after the type name in the new statement. H S Rana (UPES) Constructor and Destructor October 3, 2012 15 / 23
  • 20. Constructor and Destructor Initializing Allocated Memory We can initialize allocated memory to some known value by putting an initializer after the type name in the new statement. General form p_var = new var_type (initializer); H S Rana (UPES) Constructor and Destructor October 3, 2012 15 / 23
  • 21. Constructor and Destructor Initializing Allocated Memory Example #include <iostream> #include <new> using namespace std; int main() { int *p; try { p = new int (87); // initialize to 87 } catch (bad_alloc xa) { cout << "Allocation Failuren"; return 1; } cout << "At " << p << " "; cout << "is the value " << *p << "n"; delete p; return 0; } H S Rana (UPES) Constructor and Destructor October 3, 2012 16 / 23
  • 22. Constructor and Destructor Allocating Arrays We can allocate arrays using new operator. H S Rana (UPES) Constructor and Destructor October 3, 2012 17 / 23
  • 23. Constructor and Destructor Allocating Arrays We can allocate arrays using new operator. General form p_var = new array_type [size]; size specifies the number of elements in the array. To free an array, use delete delete [ ] p_var; H S Rana (UPES) Constructor and Destructor October 3, 2012 17 / 23
  • 24. Constructor and Destructor Allocating Arrays Example #include <iostream> #include <new> using namespace std; int main() { int *p, i; try { p = new int [10]; // allocate 10 integer array } catch (bad_alloc xa) { cout << "Allocation Failuren"; return 1; } for(i=0; i<10; i++ ) p[i] = i; for(i=0; i<10; i++) cout << p[i] << " "; delete (UPES) p; // releaseConstructor array the and Destructor H S Rana [] October 3, 2012 18 / 23
  • 25. Constructor and Destructor Allocating Objects We can allocate object using new operator.When we do this, an object is created and a pointer is returned to it. H S Rana (UPES) Constructor and Destructor October 3, 2012 19 / 23
  • 26. Constructor and Destructor Allocating Objects We can allocate object using new operator.When we do this, an object is created and a pointer is returned to it. Example #include <iostream> #include <new> #include <cstring> using namespace std; class balance { double cur_bal; char name[80]; public: void set(double n, char *s) { cur_bal = n; strcpy(name, s);} void get_bal(double &n, char *s) { n = cur_bal; strcpy(s, name);}}; H S Rana (UPES) Constructor and Destructor October 3, 2012 19 / 23
  • 27. Constructor and Destructor Allocating Objects H S Rana (UPES) Constructor and Destructor October 3, 2012 20 / 23
  • 28. Constructor and Destructor Allocating Objects Example int main(){ balance *p; char s[80]; double n; try { p = new balance; } catch (bad_alloc xa) { cout << "Allocation Failuren"; return 1;} p->set(12387.87, "Rahul Kumar"); p->get_bal(n, s); cout << s << "’s balance is: " << n; cout << "n"; delete p; return 0;} H S Rana (UPES) Constructor and Destructor October 3, 2012 20 / 23
  • 29. Constructor and Destructor Allocating Objects dynamically allocated objects may have constructors and destructors H S Rana (UPES) Constructor and Destructor October 3, 2012 21 / 23
  • 30. Constructor and Destructor Allocating Objects dynamically allocated objects may have constructors and destructors Example class balance { double cur_bal; char name[80]; public: balance(double n, char *s) { cur_bal = n; strcpy(name, s); } ~balance() { cout << "Destructing "; cout << name << "n"; } void get_bal(double &n, char *s) { n = cur_bal; strcpy(s, name);} H S Rana (UPES) Constructor and Destructor }; October 3, 2012 21 / 23
  • 31. Constructor and Destructor Allocating Objects H S Rana (UPES) Constructor and Destructor October 3, 2012 22 / 23
  • 32. Constructor and Destructor Allocating Objects Example int main() { balance *p; char s[80]; double n; // this version uses an initializer try { p = new balance (12387.87, "Rahul Kumar"); } catch (bad_alloc xa) { cout << "Allocation Failuren"; return 1; } p->get_bal(n, s); cout << s << "’s balance is: " << n; cout << "n"; delete p; returnH S0; (UPES) Rana Constructor and Destructor October 3, 2012 22 / 23
  • 33. Constructor and Destructor Const Argument An argument of a function can be declared as const. H S Rana (UPES) Constructor and Destructor October 3, 2012 23 / 23
  • 34. Constructor and Destructor Const Argument An argument of a function can be declared as const. Example int strlrn(const char *p) int length(const String &s) The qualifier const tell the compiler that the function should not modify the argument. Compiler will generate the error when this condition is violated. H S Rana (UPES) Constructor and Destructor October 3, 2012 23 / 23