Skip to content

Instantly share code, notes, and snippets.

@Tevinthuku
Last active December 5, 2016 05:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Tevinthuku/85b6062e8cb6c236a3c602ad58a5a214 to your computer and use it in GitHub Desktop.
Save Tevinthuku/85b6062e8cb6c236a3c602ad58a5a214 to your computer and use it in GitHub Desktop.
Most of what you need to know about the new keyword
// BASIC EXAMPLE OF NEW KEYWORD IN ACTION
Cars *benz = new Cars();
// the delete keyword can be placed in the destructor
delete benz;
// EXAMPLE 2;
// suppose we have an array of pointers ponting to a class
Car* smallcars[10];
// we can use the new keyword to create objects of the class
smallcars[0] = new Car;
// or suppose the Car class had other derived classes
// eg: Benz, Yoyota
smallcars[1] = new Benz;
// accessing a function
smallcars[1] ->hoot(); // BEEEEEP !!!!!
smallcars[2] = new Toyota;
smallcars[2] ->hoot(); // HOOOOONK!!!!
// THE DESTRUCTOR DELETING THE OBJECTS AND THE ARRAY OF POINTERS
Car::~Car(void) {
// deleting the objects
for (int i = 0; i < 6; i++)
{
delete smallcars[i];
}
delete[] smallcars;//delete the array of pointers
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment