Skip to end of metadata
Go to start of metadata

You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 6 Next »

In C++, new and delete are operators used for dynamic memory allocation and deallocation, while -> is an operator used for accessing members of an object through a pointer.

Here's a code snippet example of using new and delete:

int* ptr = new int;     // Allocate memory for an integer using "new"
*ptr = 42;              // Assign a value to the memory location pointed by "ptr"
cout << *ptr << endl;   // Print the value pointed by "ptr"

delete ptr;             // Deallocate the memory using "delete"

In this example, we define a pointer ptr and use the new operator to allocate memory for an integer. We then assign a value to the memory location pointed by ptr using the dereference operator (*) and print the value to the console.

Finally, we use the delete operator to deallocate the memory pointed by ptr.

Here's an example of using ->:

#include <iostream>
using namespace std;

class MyClass {
public:
    void printMessage() {
        cout << "Hello, world!" << endl;
    }
};

int main() {
    MyClass* ptr = new MyClass;   // Allocate memory for a MyClass object using "new"
    ptr->printMessage();          // Call the "printMessage" function using "->"
    delete ptr;                   // Deallocate the memory using "delete"
    
    return 0;
}

In this example, we define a class MyClass with a member function printMessage. We then define a pointer ptr and use the new operator to allocate memory for a MyClass object. Using the -> operator, we call the printMessage function on the object pointed by ptr.

Finally, we use the delete operator to deallocate the memory pointed by ptr.

Using new and delete allows you to allocate and deallocate memory dynamically at run-time, while using -> allows you to work with objects indirectly through pointers. However, working with dynamic memory requires careful management to avoid memory leaks and other errors.

Here's a breakdown of the code:

  1. Class Declaration: MyClass is a simple class with one public member function named printMessage(). This function, when called, will output "Hello, world!" to the console.

  2. Main Function: main() is the function where execution of the program starts.

  3. Dynamic Memory Allocation: Inside main(), a pointer to MyClass (ptr) is declared and allocated memory for an object of MyClass using the new operator. The new operator returns a pointer to the beginning of the new block of memory.

  4. Calling Member Function through Pointer: The printMessage() function of the MyClass object is then called using the arrow operator (->). The arrow operator is used to access the member functions and member variables of an object through a pointer.

  5. Memory Deallocation: After the printMessage() function is called, the dynamically allocated memory is deallocated using the delete operator to prevent memory leaks. After this line, ptr should not be used without first being reassigned, as it no longer points to a valid MyClass object.

  6. Return Statement: The main() function ends by returning 0, indicating successful execution of the program.

In summary, this program demonstrates the process of dynamically creating an object of a class, using it, and then cleaning it up to avoid memory leaks in C++.

Demo:

#include <iostream>
#include <string>
using namespace std; 

class Person {
public:
    string name;
    int age;

    Person(const string& pString, int pint) : name(pString), age(pInt) {}

    void display() {
        cout << "Name: " << name << ", Age: " << age << endl;
    }
};

int main() {
    // Using 'new' to dynamically allocate memory for a Person object
    Person *personPtr = new Person("John Doe", 30);

    // Using '->' to access members of the object pointed to by the pointer
    personPtr->display();

    // Using 'delete' to deallocate the memory that was previously allocated with 'new'
    delete personPtr;

    return 0;
}

This program defines a Person class with a name string and an age integer. The Person constructor takes a name and age and initializes the Person object. The display method prints out the name and age.

In the main function, we allocate memory for a Person object using the new operator and assign the address of this memory to the personPtr pointer. We then use the -> operator to call the display method of the Person object pointed to by personPtr. Finally, we use the delete operator to free the memory that was allocated for the Person object.

Please note that using new and delete is generally avoided in modern C++, in favor of smart pointers and containers, which automatically manage memory.

Here's a detailed explanation of the different parts of the code:

  1. Class Declaration: Person is a class with two public data members (name of type string and age of type int) and two public member functions. The name and age represent the name and age of a person.

  2. Class Constructor: Person has a constructor that takes two arguments: a string pString for the person's name and an integer pInt for the person's age. These parameters are used to initialize the data members name and age respectively using an initializer list (: name(pString), age(pInt)).

  3. Member Function: The display function is a member function that outputs the person's name and age to the console.

  4. Main Function: main() is the entry point where the execution of the program starts.

  5. Dynamic Memory Allocation: Inside main(), a Person pointer personPtr is declared and memory is dynamically allocated for a Person object using new. The new operator returns a pointer to the block of memory allocated.

  6. Calling Member Function through Pointer: The display() function of the Person object is then invoked using the arrow operator (->). The arrow operator is utilized to access member functions and member variables of an object via a pointer.

  7. Memory Deallocation: After calling display(), the dynamically allocated memory is deallocated using delete to prevent a memory leak. After this line, personPtr should not be used without being reassigned first, because it no longer points to a valid Person object.

  8. Return Statement: The main() function ends by returning 0, signifying that the program executed successfully.

In summary, this C++ code demonstrates the process of dynamically creating an object of a class, using it, and then cleaning it up to prevent memory leaks.

  • No labels