Skip to content

Instantly share code, notes, and snippets.

@Pipe-Runner
Created June 14, 2018 13:15
Show Gist options
  • Save Pipe-Runner/088c797b7ec31462c96dca79410fb942 to your computer and use it in GitHub Desktop.
Save Pipe-Runner/088c797b7ec31462c96dca79410fb942 to your computer and use it in GitHub Desktop.
A set of snippets for the language C++
class Animal{
public:
int legs;
string name;
Animal(string name){
this->name = name;
this->legs = 4;
}
};
int main(){
// as an object ( in stack )
Animal panda("Panda");
cout << panda.name << " " << panda.legs << endl;
// as an object pointer using new keyword ( in heap )
Animal *turtle = new Animal("Turtle");
cout << panda->name << " " << panda->legs << endl;
delete turtle;
// array of objects with constructor( stack )
Animal zoo[3] = {Animal("Panda"),Animal("Lion"),Animal("Goat")};
for( int i = 0; i < 3; i++ ){
cout << zoo[i].name << " " << zoo[i].legs << endl;
}
// array of objects with constructor( heap )
Animal *zoo[3];
zoo[0] = new Animal;
zoo[1] = new Animal("Lion",40);
zoo[2] = new Animal("Goat")
for( int i = 0; i < 3; i++ ){
cout << zoo[i].name << " " << zoo[i].legs << endl;
}
// or ( cannot use constructor ) - declared and created simultaniously
Animal *zoo;
zoo = new Animal[3]; // important line
for( int i = 0; i < 3; i++ ){
cout << zoo[i].name << " " << zoo[i].legs << endl;
}
// or ( cannot use constructor ) - declared but not created
Animal **zoo;
zoo = new Animal*[3]; // important line ( only declared )
zoo[0] = new Animal; // created
zoo[1] = new Animal("Lion",40); // created
zoo[2] = new Animal("Goat"); // created
for( int i = 0; i < 3; i++ ){
cout << zoo[i]->name << " " << zoo[i]->legs << endl;
}
return 0;
}
@Pipe-Runner
Copy link
Author

If constructor doesn't take any argument,
Animal sheep() // will throw error
Animal sheep // will work

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