C++ Creating and Accessing Objects

www.i‮.aeditfig‬com

In C++, you can create objects of a class using the new keyword to allocate memory on the heap, or simply by declaring an object on the stack. Here are some examples:

// Creating an object on the stack
MyClass obj1;
obj1.publicVar = 42;

// Creating an object on the heap
MyClass* obj2 = new MyClass();
obj2->publicVar = 10;

// Using the objects
int var1 = obj1.publicVar;
int var2 = obj2->publicVar;

// Deleting the object on the heap
delete obj2;

In this example, we've created two objects of the MyClass class: obj1 on the stack and obj2 on the heap. We've set the value of the public variable publicVar to 42 for obj1 and to 10 for obj2.

To access the public variable of the objects, we've used the dot operator with obj1 and the arrow operator with obj2.

Finally, we've deleted the object obj2 using the delete keyword to free the memory allocated on the heap.

Note that when creating objects on the heap with the new keyword, you need to remember to delete them using the delete keyword when you're done with them to avoid memory leaks.