Skip to content

New--keyword#12

Open
Butcher3Years wants to merge 13 commits intomainfrom
New--keyword
Open

New--keyword#12
Butcher3Years wants to merge 13 commits intomainfrom
New--keyword

Conversation

@Butcher3Years
Copy link
Copy Markdown
Owner

The new Keyword in C++: Dynamic Memory Allocation on the Heap

The new keyword is how you allocate memory on the heap at runtime in C++.
Unlike stack variables (which disappear when scope ends), heap-allocated objects live until you explicitly delete them.

Basic Syntax

Type* pointer = new Type;               // default constructor
Type* pointer = new Type(args);         // constructor with arguments

// For arrays
Type* arrayPtr = new Type[size];        // array of size elements (default ctor)

Real Examples

#include <iostream>
#include <string>

class Entity {
public:
    Entity() { std::cout << "Entity created (default)\n"; }
    Entity(const std::string& name) 
        : m_Name(name) 
    { 
        std::cout << "Entity created: " << m_Name << "\n"; 
    }
    ~Entity() { std::cout << "Entity destroyed: " << m_Name << "\n"; }

private:
    std::string m_Name = "Unknown";
};

int main() {
    // Single object on heap
    Entity* e1 = new Entity();              // calls default ctor
    Entity* e2 = new Entity("Cherno");      // calls parameterized ctor

    // Array on heap
    int* numbers = new int[10];             // 10 ints, uninitialized (garbage values)
    Entity* entities = new Entity[3];       // calls default ctor 3 times!

    // Don't forget to clean up!
    delete e1;                              // calls destructor + frees memory
    delete e2;
    delete[] numbers;                       // MUST use delete[] for arrays
    delete[] entities;                      // calls destructors for each element

    // std::cin.get();  // pause to see output
}

Output (something like):
text

Entity created (default)
Entity created: Cherno
Entity created (default)
Entity created (default)
Entity created (default)
Entity destroyed: Unknown
Entity destroyed: Unknown
Entity destroyed: Unknown
Entity destroyed: Cherno
Entity destroyed: Unknown

#IT JUST RETURNS A VOID POINTER

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant