Professional Documents
Culture Documents
UNIT - 4
UG02CBCA01 - OBJECT ORIENTED PROGRAMMING CONCEPTS
Pointers
Pointers are variables that store the memory addresses of other variables.
If we have a variable var in our program &var will give us its address in the memory.
Example : Printing Variable Addresses in C++
int main()
{
// declare variables
int var1 = 3;
int var2 = 24;
int var3 = 17;
pointers are used to store addresses rather than values. Here is how we can declare pointers.
int *pointVar;
Here, we have declared a pointer pointVar of the int type. We can also declare pointers in the
following way.
int* pointVar; // preferred syntax
Let's take another example of declaring pointers.
int* pointVar, p;
Here, we have declared a pointer pointVar and a normal variable p. The * operator is used after the
data type to declare pointers.
Assigning Addresses to Pointers
Here is how we can assign addresses to pointers:
int* pointVar, var;
var = 5;
// assign address of var to pointVar pointer
pointVar = &var;
Here, 5 is assigned to the variable var. And, the address of var is assigned to the pointVar pointer
with the code pointVar = &var.
Get the Value from the Address Using Pointers
To get the value pointed by a pointer, we use the * operator. For example:
int* pointVar, var;
var = 5;
// assign address of var to pointVar
pointVar = &var;
Here, pointVar and &var have the same address, the value of var will also be changed when
*pointVar is changed.
Example : Changing Value Pointed by Pointers
int main()
{
int var = 5;
int* pointVar;
// store address of var
pointVar = &var;
// print var
cout << "var = " << var << endl;
// print *pointVar
cout << "*pointVar = " << *pointVar << endl
<< endl;
// print var
cout << "var = " << var << endl;
// print *pointVar
cout << "*pointVar = " << *pointVar << endl
<< endl;
// print var
cout << "var = " << var << endl;
// print *pointVar
Manage memory effectively in C++ using new and delete operations with the help of examples. C++
allows us to allocate the memory of a variable or an array in run time. This is known as dynamic
memory allocation. In other programming languages such as Java and Python, the compiler
automatically manages the memories allocated to variables. But this is not the case in C++.
In C++, we need to deallocate the dynamically allocated memory manually after we have no use for the
variable. We can allocate and then deallocate memory dynamically using the new and delete operators
respectively.
Here, we have dynamically allocated memory for an int variable using the new operator. Notice that
we have used the pointer pointVar to allocate the memory dynamically. This is because the new
operator returns the address of the memory location. In the case of an array, the new operator returns
delete Operator
Once we no longer need to use a variable that we have declared dynamically, we can deallocate the
memory occupied by the variable. For this, the delete operator is used. It returns the memory to the
operating system. This is known as memory deallocation.
Here, we have dynamically allocated memory for an int variable using the pointer pointVar. After
printing the contents of pointVar, we deallocated the memory using delete. If the program uses a large
amount of unwanted memory using new, the system may crash because there will be no memory
available for the operating system. In this case, the delete operator can help the system from crash.
int main() {
// declare an int pointer
int* pointInt;
return 0;
}
Output
45
45.45
In this program, we dynamically allocated memory to two variables of int and float types. After
assigning values to them and printing them, we finally deallocate the memories using the code
delete pointInt;
delete pointFloat;
Dynamic memory allocation can make memory management more efficient. Especially for arrays,
where a lot of the times we don't know the size of the array until the run time.
int main()
{
int num;
cout << "Enter total number of students: ";
cin >> num;
float* ptr;
In this program, we have asked the user to enter the number of students and store it in the num
variable. Then, we have allocated the memory dynamically for the float array using new. We enter data
into the array (and later print them) using pointer notation. After we no longer need the array, we
deallocate the array memory using the code
delete[] ptr;.
Notice the use of [] after delete. We use the square brackets [] in order to denote that the memory
deallocation is that of an array.
class Student {
int age;
public:
int main()
File Handling
Files store data permanently in a storage device. With file handling, the output from a program can
be stored in a file. Various operations can be performed on the data while in the file. A stream is an
abstraction of a device where input/output operations are performed. You can represent a stream as
either a destination or a source of characters of indefinite length. This will be determined by their
usage. C++ provides you with a library that comes with methods for file handling.
fstream- This class generally represents a file stream. It comes with ofstream/ifstream capabilities.
This means it's capable of creating files, writing to files, reading from data files.
fstream library
To use the above classes of the fstream library, you must include it in your program as a header file. Of
course, you will use the #include preprocessor directive. You must also include the iostream header
file.
To Open Files
Before performing any operation on a file, you must first open it. If you need to write to the file, open it
using fstream or ofstream objects. If you only need to read from the file, open it using the ifstream
object. The three objects, that is, fstream, ofstream, and ifstream, have the open() function defined in
them.
The function takes this syntax:
open (file_name, mode);
• The file_name parameter denotes the name of the file to open.
• The mode parameter is optional. It can take any of the following values:
Value Description
ios:: app The Append mode. The output sent to the file is appended to it.
ios::ate It opens the file for the output then moves the read and write control to file's end.
ios::in It opens the file for a read.
ios::out It opens the file for a write.
ios::trunk If a file exists, the file elements should be truncated prior to its opening.
It is possible to use two modes at the same time. You combine them using the | (OR) operator.
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
fstream my_file;
my_file.open("my_file", ios::out);
if (!my_file) {
cout << "File not created!";
}
else {
cout << "File created successfully!";
my_file.close();
}
return 0;
}
Output:
Code Explanation:
1. Include the iostream header file in the program to use its functions.
2. Include the fstream header file in the program to use its classes.
3. Include the std namespace in the program to use its classes without calling it.
4. Call the main() function. The program logic should be added within the body of this function.
5. Create an instance of the fstream class and give it the name my_file.
6. Use the open() function to create a new file named my_file.txt. The file will be opened in the out
mode for writing into it.
7. Use an if statement to check whether the file has not been opened.
8. Text to print on the console if the file is not opened.
9. End of the body of the if statement.
10. Use an else statement to state what to do if the file was created.
11. Text to print on the console if the file was created.
12. Write some text to the created file.
13. Use the close() function to close the file.
14. End of the body of the else statement.
15. The program must return value upon successful completion.
16. End of the body of the main() function.
To Close Files
Once a C++ program terminates, it automatically
flushes the streams
releases the allocated memory
closes opened files.
However, as a programmer, you should learn to close open files before the program terminates.
The fstream, ofstream, and ifstream objects have the close() function for closing files. The function
takes this syntax:
void close();
To Write to Files
You can write to file right from your C++ program. You use stream insertion operator (<<) for this.
The text to be written to the file should be enclosed within double-quotes.
Output:
Code Explanation:
1. Include the iostream header file in the program to use its functions.
2. Include the fstream header file in the program to use its classes.
3. Include the std namespace in the program to use its classes without calling it.
4. Call the main() function. The program logic should be added within the body of this function.
5. Create an instance of the fstream class and give it the name my_file.
6. Use the open() function to create a new file named my_file.txt. The file will be opened in the in
mode for reading from it.
7. Use an if statement to check whether the file does not exist.
8. Text to print on the console if the file is not found.
9. End of the body of the if statement.
10. Use an else statement to state what to do if the file is found.
11. Create a char variable named ch.
12. Create a while loop for iterating over the file contents.
13. Write/store contents of the file in the variable ch.
14. Use an if condition and eof() function that is, end of the file, to ensure the compiler keeps on
reading from the file if the end is not reached.
15. Use a break statement to stop reading from the file once the end is reached.
16. Print the contents of variable ch on the console.
17. End of the while body.
18. End of the body of the else statement.
19. Call the close() function to close the file.
20. The program must return value upon successful completion.
21. End of the body of the main() function.
Each file has two associated pointers known as the file pointers. One of them is called the input
pointer or get pointer and the other us called the output pointer or put pointer. The input pointer is
used for reading from the file and the output pointer is used for writing to the file.
When we open a file for reading only (using ifstream), the input pointer is automatically set at the
beginning so that we can read from the beginning of the file. Similarly, When we open a file for
But many-a-times, we need to start reading/writing from a specific intermediate location or end of
the file. In such situation, we must move the pointer to required location. This is done using seek()
and tell() functions.
ostreamostr; ostr.open(“D:\\F2.TXT”);
// Since file is opened for writing –only, file pointer is at the end
int p = ostr.tellp(); // returns 0 (i.e. beginning of the file)
ostr.seekp(10); // Put pointer is moved to byte no. 10
p = ostr.tellp(); // returns 10
istreamistr; istr.open(“D:\\F1.TXT”);
int p = istr.tellg(); // returns 0 (i.e. beginning of the file)
ostr.seekg(ios::end); // Get pointer is moved to the last byte
p = ostr.tellg(); // returns no. of bytes (i.r. file size)
seekg() and seekp() can also be used with two arguments as follows:
seekg(offset, refposition) seekp(offset, refposition)
The parameter offset represents the no. of bytes by which the file pointer should be moved from
the position specified by second argument. The refposition takes one of the following constants
defined in the ios class: