some changes ; mostly new examples
This commit is contained in:
BIN
OOP/constructor/a.out
Executable file
BIN
OOP/constructor/a.out
Executable file
Binary file not shown.
31
OOP/constructor/car_constructor.cpp
Normal file
31
OOP/constructor/car_constructor.cpp
Normal file
@@ -0,0 +1,31 @@
|
||||
#include <iostream>
|
||||
|
||||
/*
|
||||
Here we have a more "practical" approach to Constructors ;
|
||||
We use the constructor here to print out some predefined data from a Class Object
|
||||
*/
|
||||
|
||||
using namespace std;
|
||||
|
||||
class Car {
|
||||
public:
|
||||
string brand;
|
||||
string model;
|
||||
int year;
|
||||
|
||||
Car (string x , string y , int z) {
|
||||
brand = x;
|
||||
model = y;
|
||||
year = z;
|
||||
}
|
||||
};
|
||||
|
||||
int main() {
|
||||
Car volvo("Volvo", "VolvoAuto", 1989);
|
||||
Car volkswagen("Volkswagen", "Golf", 2004);
|
||||
|
||||
cout << volvo.brand << " " << volvo.model << " " << volvo.year << "\n";
|
||||
cout << volkswagen.brand << " " << volkswagen.model << " " << volkswagen.year << "\n";
|
||||
|
||||
return 0;
|
||||
}
|
||||
34
OOP/constructor/car_outside.cpp
Normal file
34
OOP/constructor/car_outside.cpp
Normal file
@@ -0,0 +1,34 @@
|
||||
#include <iostream>
|
||||
|
||||
/*
|
||||
We copied the main function from the last example , but here we just have the Constructor outside of the class definition;
|
||||
So the Constructor then gets defined like:
|
||||
class::constructor
|
||||
Like that you can make it more "readable";
|
||||
*/
|
||||
|
||||
using namespace std;
|
||||
|
||||
class Car {
|
||||
public:
|
||||
string brand;
|
||||
string model;
|
||||
int year;
|
||||
Car(string x , string y, int z);
|
||||
};
|
||||
|
||||
Car::Car(string x, string y, int z) {
|
||||
brand = x;
|
||||
model = y;
|
||||
year = z;
|
||||
}
|
||||
|
||||
int main() {
|
||||
Car volvo("Volvo", "VolvoAuto", 1989);
|
||||
Car volkswagen("Volkswagen", "Golf", 2004);
|
||||
|
||||
cout << volvo.brand << " " << volvo.model << " " << volvo.year << "\n";
|
||||
cout << volkswagen.brand << " " << volkswagen.model << " " << volkswagen.year << "\n";
|
||||
|
||||
return 0;
|
||||
}
|
||||
20
OOP/constructor/constructor.cpp
Normal file
20
OOP/constructor/constructor.cpp
Normal file
@@ -0,0 +1,20 @@
|
||||
#include <iostream>
|
||||
|
||||
/*
|
||||
Here we have a example of a Constructor ;
|
||||
When we create a Class Object we auto-call the Constructor
|
||||
*/
|
||||
|
||||
using namespace std;
|
||||
|
||||
class MyClass {
|
||||
public:
|
||||
MyClass() { // This is the constructor!
|
||||
cout << "Construct!";
|
||||
}
|
||||
};
|
||||
|
||||
int main() {
|
||||
MyClass classobj; // When we create this the Constructor autocalls!
|
||||
return 0;
|
||||
}
|
||||
Reference in New Issue
Block a user