Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C++

Các loại Constructor trong C++


Constructor (hàm tạo) thực thi khi tạo đối tượng. Trùng tên lớp, không kiểu trả về. Dùng để khởi tạo giá trị ban đầu. Hai loại chính: Default Constructor và Parameterized Constructor.

Default Constructor

Không tham số. Nếu không cung cấp, compiler tạo implicit default constructor (giá trị 0).

Ví dụ

#include <iostream>
using namespace std;

class A {
private:
    int num1, num2;
public:
    A() {
        num1 = 5;
        num2 = 7;
    }
    void display() {
        cout << "num1 = " << num1 << endl;
        cout << "num2 = " << num2 << endl;
    }
};

int main() {
    A obj;
    obj.display();
    return 0;
}

Kết quả

num1 = 5
num2 = 7

Lớp A có default constructor gán num1=5, num2=7. Main tạo obj, gọi display().

Parameterized Constructor

Có tham số để khởi tạo đối tượng khi tạo. Gọi ngầm (implicit) hoặc tường minh (explicit).

Ví dụ

#include <iostream>
using namespace std;

class A {
private:
    int num1, num2;
public:
    A(int n1, int n2) {
        num1 = n1;
        num2 = n2;
    }
    void display() {
        cout << "num1 = " << num1 << endl;
        cout << "num2 = " << num2 << endl;
    }
};

int main() {
    A obj(3, 8);
    obj.display();
    return 0;
}

Kết quả

num1 = 3
num2 = 8

Lớp A có parameterized constructor nhận n1, n2 gán cho num1, num2. Main tạo obj(3,8), gọi display().