Last active
December 5, 2016 05:28
-
-
Save Tevinthuku/85b6062e8cb6c236a3c602ad58a5a214 to your computer and use it in GitHub Desktop.
Most of what you need to know about the new keyword
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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