Constructors - heshawacooray/OOP-Heshawa GitHub Wiki

Definition: A constructor is a special method used to initialize objects. It is automatically called when an object of a class is created. Constructors do not have a return type, not even void.

Example code:

#include <iostream>
using namespace std;

class Car {
private:
    string brand;
    int year;

public:
    // Constructor
    Car(string b, int y) {
        brand = b;
        year = y;
    }

    void display() {
        cout << "Brand: " << brand << ", Year: " << year << endl;
    }
};

int main() {
    Car car1("Toyota", 2020);
    car1.display();  

    return 0;
}
⚠️ **GitHub.com Fallback** ⚠️