Constructor က object create လုပ်တဲ့အချိန်မှာ အလိုအလျောက် run တဲ့ special method ပါ။ Object တည်ဆောက်ချိန်မှာ initial value တွေထည့်ချင်တဲ့အခါ constructor ကိုသုံးပါတယ်။ Constructor name က class name နဲ့ တူရပါတယ်။
cpp
#include <iostream>
#include <string>
using namespace std;
class Car {
public:
string brand;
int year;
Car(string b, int y) {
brand = b;
year = y;
}
void show() {
cout << brand << " - " << year;
}
};
int main() {
Car myCar("Toyota", 2024);
myCar.show();
return 0;
}Car myCar("Toyota", 2024); လို့ object create လုပ်တဲ့အချိန်မှာ constructor ကို အလိုအလျောက်ခေါ်ပါတယ်။ Constructor က parameter တွေကို attribute တွေထဲ သိမ်းပေးပါတယ်။
You should see
Toyota - 2024Info
Constructor မှာ return type မရေးရပါ။ void Car() လို့ရေးရင် constructor မဟုတ်တော့ပါ။