C++ constructor function example

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();
}
Category >> C/C++  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
<pre><code> 
String foo = "bar";
</code></pre>

Leave a comment

*