A constructor in C++ is a special method that is automatically called when an object of a class is created.
It is generally used to initialize the object's attributes with default or starting values.
void).public (usually, though advanced patterns might use private constructors).#include <iostream> using namespace std;class MyClass { public: // This is the constructor MyClass() { cout << "Object created! Constructor called.\n"; } };
int main() { MyClass myObj; // Constructor is called automatically here! return 0; }
Notice that we didn't explicitly call myObj.MyClass(). The constructor ran the exact moment MyClass myObj; was executed.
Constructors can also take parameters, just like regular functions. This is incredibly useful for setting initial values for attributes right when the object is created.
#include <iostream> #include <string> using namespace std;class Car { public: string brand; string model; int year; // Constructor with parameters Car(string x, string y, int z) { brand = x; model = y; year = z; } };
int main() { // Create objects and pass values to the constructor 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; }
This code is much cleaner than creating an object and then setting each attribute one by one on separate lines!
Which of the following is TRUE about a constructor in C++?