Here is a example showing how to use constructor function in C++.
#include <iostream> using namespace std; class Car { public: int number; // a construct without parameter Car(){ number = 123; //assign a default value } // a construct with parameter Car(int x){ number = x; } void Create() { cout << "Car created, number is: " << number << "\n" ; } }; int main() { Car x(456); //equals to Car *z = new Car(63746); x.Create(); Car y; y.Create(); Car *z; z = new Car(789); z->Create(); } |
If no constructor is defined, can use Car x = {123456};
#include <iostream> using namespace std; class Car { public: int number; void Create() { cout << "Car created, number is: " << number << "\n" ; } }; int main() { Car x = {123456}; x.Create(); Car *y = new Car(); y->Create(); } |