C++ new operator

Created By: chatGPT

C++ provides the new operator to dynamically allocate memory for an object or an array. This memory is allocated from the heap, and it allows for flexible memory management during runtime. Using the new operator, you can create instances of classes without determining their size at compile time. Remember to release the memory you allocate with new using the delete operator to avoid memory leaks.
// Allocating a single object
MyClass* obj = new MyClass();

// Deallocating the memory
delete obj;
When you want to allocate an array of objects, you can use new[]. This ensures that memory for multiple instances is allocated at once, and it is essential to use delete[] to free that memory correctly.
// Allocating an array of objects
MyClass* objArray = new MyClass[10];

// Deallocating memory for the array
delete[] objArray;
It's important to handle exceptions when using new, as it can throw a std::bad_alloc exception if memory allocation fails. You can use a try-catch block to gracefully handle such situations.
try {
    MyClass* obj = new MyClass();
} catch (const std::bad_alloc& e) {
    std::cerr << "Memory allocation failed: " << e.what() << std::endl;
}
Understanding the scope of dynamically allocated memory is crucial. The objects created with new persist until you explicitly deallocate them, unlike automatic storage duration objects that are cleared when they go out of scope.
void example() {
    MyClass* obj = new MyClass(); // obj is alive after this function ends.
    delete obj; // Must delete before leaving to prevent memory leak.
}
Introduction And SetupVariablesData TypesIntFloatDoubleCharBoolStringVoidConstantsOperatorsArithmetic OperatorsRelational OperatorsLogical OperatorsBitwise OperatorsAssignment OperatorsTernary OperatorControl FlowIf StatementElse StatementElse If StatementSwitch StatementFor LoopWhile LoopDo While LoopBreak StatementContinue StatementGoto StatementFunctionsFunction DeclarationFunction DefinitionFunction OverloadingInline FunctionsDefault ArgumentsRecursionPass By ValuePass By ReferenceData StructuresArraysMultidimensional ArraysStructsEnumsUnionsClassesObjectsMember FunctionsConstructorsDestructorsAccess SpecifiersPublicPrivateProtectedInheritancePolymorphismFunction OverridingVirtual FunctionsPure Virtual FunctionsOperator OverloadingTemplatesNamespaceCommentsSingle Line CommentsMulti Line CommentsSyntaxSemicolonCurly BracesParenthesesEvent HandlingCinCoutError HandlingTry BlockCatch BlockThrow StatementException HandlingPreprocessor DirectivesInclude GuardsMacro DefinitionsInline AssemblyStatic KeywordsExtern KeywordsConst KeywordsVolatile KeywordsFriend FunctionStatic MemberThis PointerDynamic Memory AllocationNew OperatorDelete Operator