0% found this document useful (0 votes)
38 views11 pages

Array of Objects in C--(Unit-1).Docx

Uploaded by

julee9800
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)
38 views11 pages

Array of Objects in C--(Unit-1).Docx

Uploaded by

julee9800
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/ 11

Array of objects in C++

array of objects is a collection of objects of the same class type that are stored in contiguous
memory locations. Since each item in the array is an instance of the class, each one's member
variables can have a unique value. This makes it possible to manage and handle numerous
objects by storing them in a single data structure and giving them similar properties and
behaviors.No memory or storage is allocated when a class is defined; only the object's
specification is defined. We must create objects in order to use the data and access the class's
defined functions.
array of objects as a single variable that can hold multiple values. Each value is stored in a
separate element of the array, and each element can be accessed by its index.
Arrays in C++ are typically defined using square brackets [] after the type. The index of the
array, which ranges from 0 to n - 1, can be used to access each element.
Syntax for declaring an array of objects in C++:
class className {
//variables and functions
};

className arrayName[arraySize];
where,
className is the name of the class that the objects belong to.
arrayName is the name of the array of objects.
arraySize is the number of objects in the array or the size of array, specified as a constant
expression.
Example
#include<iostream>

using namespace std;

class MyClass {

private:

int data;

public:
void initialize(int i){

data = i;

void method(int i){

cout<<"object "<<i+1<<endl;}

};

int main(){

MyClass array_of_objects[5];

for(int i=0; i<5; i++){

array_of_objects[i].initialize(i+1);

for(int i=0; i<5; i++){

array_of_objects[i].method(i);}

}
Output:
object 1
object 2
object 3
object 4
object 5
Advantages of Array of Objects:
1. The array of objects represent storing multiple objects in a single name.
2. In an array of objects, the data can be accessed randomly by using the index number.
3. Reduce the time and memory by storing the data in a single variable.
Disadvantages of Array of Objects:
1. The main disadvantage with arrays of objects is that the constructor runs for each object.
If the default constructor doesn’t do the right thing for multiple objects in the array, we
have to specify the constructor arguments for each element at the time the array is
declared, which we wouldn’t have to do if we allocated an array of object pointers, and
allocated objects as needed.

What are Pointers?

Pointer is a variable whose value is the address of another variable. Like any variable or
constant, you must declare a pointer before you can work with it. The general form of a pointer
variable declaration is −

type *var-name;
Following are the valid pointer declaration −
int *ip; // pointer to an integer
double *dp; // pointer to a double
float *fp; // pointer to a float
char *ch // pointer to character
Pointers in C++
Pointers have many but easy concepts and they are very important to C++ programming. There
are following few important pointer concepts which should be clear to a C++ programmer −

Sr.N
Concept & Description
o

Null Pointers
1 C++ supports null pointer, which is a constant with a value of zero defined in several standard
libraries.

Pointer Arithmetic
2
There are four arithmetic operators that can be used on pointers: ++, --, +, -

Pointers vs Arrays
3
There is a close relationship between pointers and arrays.

4 Array of Pointers
You can define arrays to hold a number of pointers.

Pointer to Pointer
5
C++ allows you to have pointer on a pointer and so on.

Passing Pointers to Functions


6 Passing an argument by reference or by address both enable the passed argument to be
changed in the calling function by the called function.

Return Pointer from Functions


7 C++ allows a function to return a pointer to local variable, static variable and dynamically
allocated memory as well.

What is a Pointer to an object?

A pointer to an object in C++ is a variable that contains an object's memory address.


Pointers provide indirect access to and control over memory items. They are especially
helpful when we need to dynamically allocate memory for objects, build linked lists or trees,
or pass objects by reference to methods without making duplicates.

The behavior of an object pointer is identical to that of a variable pointer. But in this case,
the object's address is kept instead of the variables. When a class object is formed in
the main function, a pointer variable is declared similarly to the variable itself. Using a data
type for the pointer is not recommended when generating a pointer to an object. Instead, we
must make use of the object pointer's class name. The -> symbol must be used to call a class
member function using a Pointer in the main function.

Syntax:

It has the following syntax:


Declaring a Pointer to an Object:

We declare a pointer to an object using the object's class name followed by an asterisk
(*) and the pointer name.

ClassName *pointer name; // Declaration of a pointer to an object


Creating Objects and Pointers:

Objects are created using the new keyword, which dynamically allocates memory for the
object. After that, the Pointer is assigned the memory address of the newly created object.

ClassName *objPtr = new ClassName(); // Creating an object and assigning its address to the
pointer

Accessing Object Members via Pointer:


We can use the arrow operator (->) to access members (variables and functions) of the
object through the pointer.
objects->memberFunction(); // Calling a member function through the pointer
int value = objPtr->memberVariable; // Accessing a member variable through the pointer
Dereferencing a Pointer:

We "dereference" the pointer using the asterisk (*) operator to access the object itself
(rather than its members).

1. ClassNameobj = *objPtr; // Dereferencing the pointer to get the object


Deleting Objects and Pointers:
When we're done with the dynamically allocated object, freeing the memory using the delete
keyword is important. Failing to do so can result in memory leaks.
1. delete objects; // Deleting the dynamically allocated object
Null Pointers:
Pointers can also hold a special value, nullptr, which indicates that they are not pointing to
a valid memory address.
1. ClassName *nullPtr = nullptr; // Initializing a pointer with a null value

▪ References vs Pointers
▪ You cannot have NULL references. You must always be able to assume that a
reference is connected to a legitimate piece of storage.
▪ Once a reference is initialized to an object, it cannot be changed to refer to
another object. Pointers can be pointed to another object at any time.
▪ A reference must be initialized when it is created. Pointers can be initialized at
any time.
▪ Creating References in C++

Suppose we have the following example −


int i = 17;
We can declare reference variables for i as follows.
int& r = i;

the & in these declarations as reference. Thus, read the first declaration as "r is an
integer reference initialized to i" and read the second declaration as "s is a double
reference initialized to d.". Following example makes use of references on int and
double

References are usually used for function argument lists and function return values. So following
are two important subjects related to C++ references which should be clear to a C++ programmer

Sr.No Concept & Description

References as Parameters
1
C++ supports passing references as function parameter more safely than parameters.

Reference as Return Value


2
You can return reference from a C++ function like any other data type.

Dynamic allocation of Objects in C++


two operators new and delete to perform memory allocation and de-allocation. These types of
objects are called dynamic objects. The new operator is used to create objects dynamically and
the delete operator is used to delete objects dynamically. The dynamic objects can be created
with the help of pointers.
Syntax:
ClassName *ptr_obj; // pointer to object
ptr_obj = new ClassName // Dynamic object creation
delete ptr_obj; // Delete object dynamically
Reference to Dynamic Objects
The address of dynamic objects returned by the new operator can be dereferenced and a
reference to them can be created.
Syntax:
ClassName &RefObj = * (new ClassName);
The reference to object RefObj can be used as a normal object. The memory allocated to such
objects cannot be released except during the termination of the program.
Below is the program of Reference to Dynamic Objects in C++.
Pointer Operators
A pointer variable is a variable that stores the address of another variable or in other a pointer
variable points to the variable whose address is stored inside it.
Syntax:
int *pointer_name;
There are mainly two types of Pointer operators mainly used:
● Address of operator (&)
● The indirection operator/Dereference operator (*)

1. Address-of operator (&)


The Address-of operator (&) is a unary operator that returns the memory address of its
operand which means it stores the address of the variable, which depicts that we are only storing
the address not the numerical value of the operand. It is spelled as the address of the variable.
Syntax:
gfg = &x; // the variable gfg stores the address of the variable x.

C++ Program to demonstrate


// the use of Address-of operator (&)
#include <iostream>
usingnamespace std;

int main()
{

int x = 20;

// Pointer pointing towards x


int* ptr = &x;

cout << "The address of the variable x is :- " << ptr;


return 0;
}

Output
The address of the variable x is :- 0x7fff412f512c
2. The indirection operator/Dereference operator (*)
The indirection/ dereference operator is a unary operator that returns the value of the variable
present at the given address. It is completely opposite to the address-of operator. It is spelled as
a value pointed at the address.
Example:
● C++

// C++ Program to Demonstrate


// the indirection/Dereference operator
#include <bits/stdc++.h>
usingnamespace std;

int main()
{

int self_paced = 3899;


int* price;

// Pointer storing address of self_paced


price = &self_paced;

cout
<< "The value stored at the variable price is Rs : "
<< (*price);

return 0;
}

Output
The value stored at the variable price is Rs : 3899
Scope Resolution Operator in C++
The scope resolution operator is used to reference the global variable or member function that is
out of scope. Therefore, we use the scope resolution operator to access the hidden variable or
function of a program. The operator is represented as the double colon (::) symbol.
For example, when the global and local variable or function has the same name in a program,
and when we call the variable, by default it only accesses the inner or local variable without
calling the global variable. In this way, it hides the global variable or function. To overcome this
situation, we use the scope resolution operator to fetch a program's hidden variable or function.
Uses of the scope resolution Operator
1. It is used to access the hidden variables or member functions of a program.
2. It defines the member function outside of the class using the scope resolution.
3. It is used to access the static variable and static function of a class.
4. The scope resolution operator is used to override function in the Inheritance.
Program to access the hidden value using the scope resolution (::) operator
Program1.cpp
1. #include <iostream>
2. using namespace std;
3. // declare global variable
4. int num = 50;
5. int main ()
6. {
7. // declare local variable
8. int num = 100;
9.
10. // print the value of the variables
11. cout << " The value of the local variable num: " << num;
12.
13. // use scope resolution operator (::) to access the global variable
14. cout << "\n The value of the global variable num: " << ::num;
15. return 0;
16. }
Output
The value of the local variable num: 100
The value of the global variable num: 50

You might also like