OOPlecture7
OOPlecture7
Allocation
CSE-213
Object Oriented Programming Language
Objects Memory Allocation in C++
► We can allocate and then deallocate memory dynamically using the new and
delete operators respectively.
C++ new Operator
► The new operator allocates memory Here, we have dynamically allocated memory for
to a variable. For example, an int variable using the new operator.
// declare an int pointer
Notice that we have used the pointer pointVar to
int* pointVar; allocate the memory dynamically. This is because
// dynamically allocate memory the new operator returns the address of the
memory location.
// using the new keyword
pointVar = new int;
// assign value to allocated memory
*pointVar = 45;
► In the case of an array, the new operator returns the address of the first
element of the array.
► From the example above, we can see that the syntax for using the new
operator is
float* ptr;
// memory allocation of num number of floats
ptr = new float[num];
cout << "Enter GPA of students." << endl;
for (int i = 0; i < num; ++i) {
cout << "Student" << i + 1 << ": ";
cin >> *(ptr + i);
Output
► 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.
Example 3: C++ new and delete Operator for Objects
► #include <iostream> int main() {
► using namespace std;
// dynamically declare Student object
Student* ptr = new Student();
► class Student {
► private: // call getAge() function
► int age; ptr->getAge();
► void getAge() {
► cout << "Age = " << age << endl;
► }
► };
► Output
Age = 12
► In this program, we have created a Student class that has a private variable age.
► We have initialized age to 12 in the default constructor Student() and print its value
with the function getAge().
► In main(), we have created a Student object using the new operator and use the
pointer ptr to point to its address.
► The moment the object is created, the Student() constructor initializes age to 12.
ptr->getAge();
► Notice the arrow operator ->. This operator is used to access class members using
pointers.
Thank you !!!