...
Code Block | ||
---|---|---|
| ||
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"
ptr = nullptr; // // Set the pointer to nullptr after deletion
|
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.
...
Code Block | ||
---|---|---|
| ||
#include <iostream> using namespace std; class MyClass { public: void printMessage() { cout << "Hello, world!" << endl; } }; int main() { // Allocate memory for a MyClass object using "new" MyClass* ptr = new MyClass; // Call the "printMessage" function using "->" ptr->printMessage(); // Deallocate the memory using "delete" delete ptr; // Set the pointer to nullptr after deletion ptr = nullptr; 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
.
...
Code Block | ||
---|---|---|
| ||
#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; personPtr = nullptr; 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.
...