0% found this document useful (0 votes)
51 views

Array of Objects

This document discusses pointers to objects and object members in C++. It begins with an example demonstrating dynamic memory allocation of an object using new and delete. It then discusses arrays of objects and provides an example. It explains that pointers can reference object members like data members and member functions. Examples are given for pointers to data members, accessing members through objects and object pointers. The role of the this pointer is described. Finally, the set_new_handler function for setting a new-handler callback is summarized.

Uploaded by

Harshada Jadhav
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
51 views

Array of Objects

This document discusses pointers to objects and object members in C++. It begins with an example demonstrating dynamic memory allocation of an object using new and delete. It then discusses arrays of objects and provides an example. It explains that pointers can reference object members like data members and member functions. Examples are given for pointers to data members, accessing members through objects and object pointers. The role of the this pointer is described. Finally, the set_new_handler function for setting a new-handler callback is summarized.

Uploaded by

Harshada Jadhav
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

#include <iostream>

using namespace std;


class data
{
int x,y;
public:
data()
{
cout<<"\n constructor called";
x=10;
y=20;
}
~data()
{
cout<<"\n destructor called";
}
void display()
{
cout<<"\n x=: "<<x;
cout<<"\n y=: "<<y<<endl;
}

};
int main ()
{
data *d; //declaration of object pointer
d=new data; //dynamic object
d->display();
cout<<d;
delete d; //deleting dynamic object
cout<<d;
return 0;
}
Array of Objects:
suppose we have 50 students in a class and we have to input the name
and marks of all the 50 students. Then creating 50 different objects and
then inputting the name and marks of all those 50 students is not a good
option. In that case, we will create an ​array of objects as we do in case of
other data-types.
The array of type class contains the objects of the class as its individual elements. Thus,
an array of a class type is also known as an array of objects. An array of objects is
declared in the same way as an array of any built-in data type.
The syntax for declaring an array of objects is

class_name array_name [size] ;

Example 1:
#include <iostream>
using namespace std;
class books
{
public:
char title [30];
float price ;
void getdata ();
void putdata ();
};
void books :: getdata ()
{
cout<<"Title:";
cin>>title;
cout<<"Price:";
cin>>price;
}

void books :: putdata ()


{
cout<<"Title:"<<title<< "\n";
cout<<"Price:"<<price<< "\n";
}
int main ()
{
const int size=3 ;
books book[size] ;
for(int i=0;i<size;i++)
{
cout<<"Enter details of book "<<(i+1)<<"\n";
book[i].getdata();
}
for(int i=0;i<size;i++)
{
cout<<"\n Book "<<(i+1)<<"\n";
book[i].putdata() ;
}
return 0;
}
Output:-
Enter details o£ book 1
Title:c++
Price:450
Enter details o£ book 2
Title:java
Price:590
Enter details o£ book 3
Title:c
Price:390
Book 1
Title:c++
Price:450
Book 2
Title:java
Price:590
Book 3
Title:c
Price:390

Pointers to Object members:


Just like pointers to normal variables and functions, we can have pointers to class
member functions and member variables. It can be accessed in two ways:-
1.Access through objects:
2.Access through objects pointers:

Defining a Pointer of Class type


class Simple
{
public:
int a;
};

int main()
{
Simple obj;
Simple* ptr; // Pointer of class type
ptr = &obj;

cout << obj.a;


cout << ptr->a; // Accessing member with pointer
}

Pointer to Data Members of Class


We can use pointer to point to class data members (Member variables).
1.Syntax for Declaration :

datatype class_name :: *pointer_name;

2. Syntax for Assignment :

pointer_name = &class_name :: datamember_name;


3. Both declaration and assignment can be done in a single statement too.

datatype class_name::*pointer_name = &class_name::datamember_name ;

Using Pointers with Objects

For accessing normal data members we use the dot . operator with object and -> qith
pointer to object. But when we have a pointer to data member, we have to dereference
that pointer to get what its pointing to, hence it becomes,

Object.*pointerToMember

and with pointer to object, it can be accessed by writing,


ObjectPointer->*pointerToMember

Example:
class Data
{
public:
int a;
void print()
{
cout << "a is "<< a;
}
};
int main()
{
Data d, *dp;
dp = &d; ​// pointer to object

int Data::*ptr=&Data::a; // pointer to data member 'a'

d.*ptr=10;
d.print();

dp->*ptr=20;
dp->print();
}

Pointer to Member Functions of Class

Pointers can be used to point to class's Member functions.

Syntax:

return_type (class_name::*ptr_name) (argument_type) =


&class_name::function_name;

Example

class Data
{
public:
int f(float)
{
return 1;
}
};

int (Data::*fp1) (float) = &Data::f; // Declaration and assignment


int (Data::*fp2) (float); // Only Declaration

int main()
{
fp2 = &Data::f; // Assignment inside main()
}
Pointer to Member Functions of Class
Pointers can be used to point to class's Member functions.

Example:
#include <iostream>
using namespace std;
class demo
{
int y;
public:
int a,b;
int func(int z)
{
a=z;
return z;
}
};
int main ()
{
demo obj;
int demo::*ptr; // pointer to data member
ptr=&demo::a; /​/address to data member a is assigned to pointer
access through object
obj.*ptr=10;
cout<<"a in object after o1.*ptr=10 is:"<<obj.*ptr<<endl;
demo *ptrobj; //pointer to object of the class demo
ptrobj=&obj; /​/access though object pointer
ptrobj->*ptr=10;
cout<<"a in obj after ptrobj->*ptr is "<<ptrobj->*ptr<<endl;

int(demo::*ptr_func) (int);
ptr_func=&demo::func; /​/pointer to member function func()

(obj.*ptr_func)(5); //access through object


cout<<"a in object , after (obj.*ptr_func)(5)= : "<<obj.a<<endl;
(ptrobj->*ptr_func)(5); //access though object pointer
cout<<"a in object , after (obj->*ptr_func)(5)= : "<<obj.a<<endl;
return 0;
}

a in object after o1.*ptr=10 is:10


a in obj after ptrobj->*ptr is 10
a in object , after (obj.*ptr_func)(5)= : 5
a in object , after (obj->*ptr_func)(5)= : 5

Example:-

#include <iostream>
using namespace std;

class X {
public:
int a;
void f(int b)
{
cout << "The value of b is "<< b << endl;
}
};

int main() {

// declare pointer to data member


int X::*ptiptr = &X::a;

// declare a pointer to member function


void (X::* ptfptr) (int) = &X::f;
// create an object of class type X
X xobject;

// initialize data member


xobject.*ptiptr = 10;

cout << "The value of a is " << xobject.*ptiptr << endl;

// call member function


(xobject.*ptfptr) (20);
}

This pointer:
To understand ‘this’ pointer, it is important to know that how objects look at
functions and data members of a class.
1. Each object gets its own copy of the data member.
2. All access the same function definition as present in the code segment.
Meaning each object gets its own copy of data members and all objects
share single copy of member functions.
Then now question is that if only one copy of each member function exists
and is used by multiple objects, how are the proper data members are
accessed and updated?
Compiler supplies an implicit pointer along with the functions names as
‘this’.
The ‘this’ pointer is passed as a hidden argument to all nonstatic member
function calls and is available as a local variable within the body of all
nonstatic functions. ‘this’ pointer is a constant pointer that holds the
memory address of the current object. ‘this’ pointer is not available in static
member functions as static member functions can be called without any
object (with class name).
Following are the situations where ‘this’ pointer is
used:
1) When local variable’s name is same as member’s
name
#include<iostream>
using namespace std;

/* local variable is same as a member's name */


class Test
{
private:
int x;
public:
void setX (int x)
{
// The 'this' pointer is used to retrieve the object's x
// hidden by the local variable 'x'
this->x = x;
}
void print() { cout << "x = " << x << endl; }
};

int main()
{
Test obj;
int x = 20;
obj.setX(x);
obj.print();
return 0;
}
2) To return reference to the calling object
Another example of using this pointer is to return the reference of current object so that
you can chain function calls, this way you can call all the functions for the current object
in one go. Another important point to note in this program is that I have incremented the
value of object’s num in the second function and you can see in the output that it
actually increment the value that we have set in the first function call. This shows that
the chaining is sequential and the changes made to the object’s data members retains
for further chaining calls.
/* Reference to the calling object can be returned */
Test& Test::func ()
{
// Some processing
return *this;
}
When a reference to a local object is returned, the returned reference can
be used to ​chain function calls​ on a single object.

Example:
#include<iostream>
using namespace std;

class Test
{
private:
int x;
int y;
public:
Test(int x = 0, int y = 0)
{
this->x = x;
this->y = y;
}
Test &setX(int a)
{
x = a;
return *this;
}
Test &setY(int b)
{
y = b;
return *this;
}
void print()
{
cout << "x = " << x << " y = " << y << endl;
}
};

int main()
{
Test obj1(5, 5);

// Chained function calls. All calls modify the same object


// as the same object is returned by reference
obj1.setX(10).setY(20);

obj1.print();
return 0;
}
Function set_new_handler():
Sets new_p as the ​new-handler function.​

The new-handler function is a function which is called by the default


allocation functions (​operator new and ​operator new[]​) when they fail to
allocate storage.

The ​new-handler function may try to make more storage available for a
new attempt to allocate the storage. If -and only if- the function succeeds in
making more storage available, it may return. Otherwise it shall either throw
a ​bad_alloc exception (or a derived class) or terminate the program (such
as by calling​ ​abort​ or​ ​exit​).

If the ​new-handler function returns (i.e., it made more storage available), it


may be called repeatedly for as long as the ​allocation function fails to
allocate the requested storage, or until the ​new-handler function does not
return or is replaced.

Before this function is called by the program for the first time, or if new_p is
a ​null-pointer​, the default ​allocation functions directly throw ​bad_alloc on
failure.

Parameters
new_p
Function that takes no arguments and returns no value (void).
The function can make more storage available, or throw an exception, or
terminate the program.
If this is a ​null-pointer,​ the ​new-handler function is reset to none (and
bad_alloc​ is thrown instead).
new_handler is a function pointer type for functions that take no arguments
and return no value.
Return value
The value of the current ​new-handler function if this has already been set
by this function previously, or a ​null-pointer if this is the first call to
set_new_handler (or if it was reset by a previous call).

new_handler is a function pointer type taking no arguments and returning


no value.

// new_handler example
#include <iostream> // std::cout
#include <cstdlib> // std::exit
#include <new> // std::set_new_handler

void no_memory () {
std::cout << "Failed to allocate memory!\n";
std::exit (1);
}

int main () {
std::set_new_handler(no_memory);
std::cout << "Attempting to allocate 1 GiB...";
char* p = new char [1024*1024*1024];
std::cout << "Ok\n";
delete[] p;
return 0;
}
o/p:-

Attempting to allocate 1 GiB... Ok

You might also like