(+84) 236.3827111 ex. 402

Hàm khởi tạo trong lớp dẫn xuất


Hàm khởi tạo trong kế thừa

- Khi khai báo đối tượng lớp dẫn xuất->gọi hàm khởi tạo lớp dẫn xuất

- Thứ tự gọi: hàm tạo lớp cơ sở, sau đó đến hàm tạo lớp dẫn xuất.

- Cú pháp

([Các tham số]):([Các đối số]){

…//Khởi tạo các thuộc tính bổ sung của lớp dẫn xuất

}

Ví dụ:

- Định nghĩa lớp Car có 3 thuộc tính speed, mark và price với 2 hàm khởi tạo.

- Định nghĩa lớp Bus có thêm thuộc tính label là số hiệu của tuyến xe buýt. Lớp Bus sẽ được cài đặt hai hàm khởi tạo tường minh, gọi đến 2 hàm khởi tạo của lớp Car.

//Định nghĩa lớp Car

class Car{

private:

int speed;

string mark;

float price;

public:

Car();

Car(int speed, string mark, float price);

};

Car::Car(){

this->speed=0;

this->mark=””;

this->price=0;

}

Car::Car(int speed, string mark, float price){

this->speed=speed;

this->mark=mark;

this->price=price;

}

//Định nghĩa lớp Bus

class Bus:public Car{

private:

int label;

public:

Bus();

Bus(int speed, string mark, float price, int label);

};

Bus::Bus():Car(){

this->label=0;

}

Bus::Bus(int speed, string mark, float price, int label):

Car(spees,mark,price){

this->label=label;

}