when to use new keyword in c++ code example
Example 1: new keyword in cpp
#include <iostream>
#include <string>
using String = std::string;
class Entity
{
private:
String m_Name;
public:
Entity() : m_Name("Unknown") {}
Entity(const String& name) : m_Name(name) {}
const String& GetName() const {
return m_Name;
};
};
int main() {
// new keyword is used to allocate memory on heap
int* b = new int; // new keyword will call the c function malloc which will allocate on heap memory = data and return a ptr to that plaock of memory
int* c = new int[50];
Entity* e1 = new Entity;//new keyword Not allocating only memory but also calling the constructor
Entity* e = new Entity[50];
//usually calling new will call underlined c function malloc
//malloc(50);
Entity* alloc = (Entity*)malloc(sizeof(Entity));//will not call constructor only allocate memory = memory of entity
delete e;//calls a c function free
Entity* e3 = new(c) Entity();//Placement New
}
Example 2: new class * [] c++
/*
Keyword "this"
You can use keyword "this" to refer to this instance inside a class definition.
One of the main usage of keyword this is to resolve ambiguity between the names of
data member and function parameter. For example:
*/
class Circle {
private:
double radius; // Member variable called "radius"
......
public:
void setRadius(double radius) { // Function's argument also called "radius"
this->radius = radius;
// "this.radius" refers to this instance's member variable
// "radius" resolved to the function's argument.
}
......
}