Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

C++ Interview questions based on constructors/ Destructors


C++ interview questions on Constructors

What is a constructor?

Constructor คือฟังก์ชันของคลาสที่มีชื่อเดียวกับคลาส Constructor ถูกเรียกเมื่อสร้างออบเจกต์ มี 3 ประเภท −

  • Default constructor
  • Parameterized constructor
  • Copy constructor

Syntax

class cl_name{   cl_name(){     //This is constructor..   } }

What is a destructor?

Destructor คือเมธอดของคลาสที่มีชื่อเดียวกับคลาส แต่นำหน้าด้วยสัญลักษณ์ tilde ~ ถูกเรียกเมื่อจบโปรแกรมหรือเมื่อออบเจกต์ถูกทำลายหรือออกจากขอบเขต (scope)

Syntax

class cl_name{   ~ cl_name(){} //destructor }

What is the use of constructor?

Constructor คือเมธอดที่ชื่อเดียวกับคลาส ใช้สำหรับ initialize ออบเจกต์เมื่อสร้างด้วยคำสั่ง new

เมื่อสร้างออบเจกต์ ตัวแปรจะถูก initialize เป็นชunks ของหน่วยความจำและค่าเริ่มต้นถ้ามี

What is the use of destructor?

Destructor คือเมธอดที่ชื่อเดียวกับคลาสนำหน้าด้วย ~ ใช้สำหรับ deallocate หน่วยความจำเมื่อโค้ดออกจากขอบเขตของออบเจกต์หรือลบด้วย delete keyword

เมื่อออบเจกต์ถูกลบ Destructor จะถูกเรียกและ deallocate บล็อกหน่วยความจำทั้งหมดที่สร้างตอนสร้างออบเจกต์

What is the order of constructor execution in C++?

Constructor ถูกเรียกเมื่อสร้างออบเจกต์ของคลาส ลำดับการเรียก constructor เหมือนกับลำดับชั้นของการสืบทอด (inheritance hierarchy) หมายถึงออบเจกต์ของ base class ถูกเรียกก่อน แล้วค่อย child class ตามลำดับ

What is the order of destructor execution in C++?

Destructor ถูกเรียกในลำดับย้อนกลับของ constructor และเรียกเมื่อออบเจกต์ถูกลบ ลำดับการเรียก destructor เป็นตรงข้ามกับลำดับชั้นของการสืบทอด หมายถึงออบเจกต์ของ child class ถูกทำลายก่อน แล้วค่อย parent class ตามลำดับ

Is the default constructor created even if we create any other constructor?

Constructor จะถูกสร้างโดยคอมไพเลอร์โดยอัตโนมัติ หากโปรแกรมเมอร์ไม่ได้กำหนด constructor เอง หากโปรแกรมเมอร์กำหนด constructor เอง คอมไพเลอร์จะไม่สร้าง default constructor ให้