Konstruktorlar parametrlarni (odatdagi funktsiyalar kabi) ham olishi mumkin, bu esa atributlar uchun boshlang'ich qiymatlarni belgilashda foydali bo'lishi mumkin.
#include 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 carObj1("BMW", "X5", 1999);
Car carObj2("Ford", "Mustang", 1969);
// Print values
cout << carObj1.brand << " " << carObj1.model << " " << carObj1.year << "\n";
cout << carObj2.brand << " " << carObj2.model << " " << carObj2.year << "\n";
return 0;
}
BMW X5 1999
Ford Mustang 1969
Vazifalar singari, konstruktorlarni ham sinfdan tashqari aniqlash mumkin. Birinchidan, sinf ichidagi konstruktorni e'lon qiling va keyin sinf nomini ko'rsatib, uni sinfdan tashqarida aniqlang, so'ngra o'lchamlarni aniqlash :: operatori, keyin konstruktorning nomi (sinf bilan bir xil):
#include 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 carObj1("BMW", "X5", 1999);
Car carObj2("Ford", "Mustang", 1969);
cout << carObj1.brand << " " << carObj1.model << " " << carObj1.year << "\n";
cout << carObj2.brand << " " << carObj2.model << " " << carObj2.year << "\n";
return 0;
}