Skip to content

FAQ - Câu hỏi thường gặp

🤔 Câu hỏi chung về C++

Q: C++ khó học không?

A: C++ có độ khó trung bình đến cao, nhưng với lộ trình học tập có hệ thống:

  • Tuần 1-2: Cú pháp cơ bản, biến, vòng lặp
  • Tuần 3-4: Hàm, mảng, chuỗi
  • Tuần 5-8: OOP (classes, inheritance, polymorphism)
  • Tuần 9-12: STL, templates, advanced topics

Q: Tại sao nên học C++?

A:

  • Hiệu suất cao: Gần với hardware, tốc độ nhanh
  • Đa dụng: Game, embedded, system programming, desktop apps
  • Nền tảng tốt: Hiểu sâu về memory, performance
  • Cơ hội việc làm: Nhiều công ty lớn sử dụng C++

Q: C++ vs Python/Java khác gì?

A:

Đặc điểmC++PythonJava
Tốc độRất nhanhChậmTrung bình
Học tậpKhóDễTrung bình
MemoryManualAutoAuto (GC)
PlatformNativeInterpretedJVM

🔧 Cú pháp và Cơ bản

Q: Khi nào dùng #include <iostream> vs #include "myheader.h"?

A:

  • <>: System headers, STL headers
  • "": User-defined headers, project files

Q: using namespace std có tốt không?

A:

  • Trong học tập: OK, code ngắn gọn
  • Trong dự án thực: Nên tránh, dùng std::cout thay vì using namespace std

Q: Sự khác biệt giữa ++ii++?

A:

cpp
++i;  // Pre-increment: tăng i trước, trả về giá trị mới
i++;  // Post-increment: trả về giá trị cũ, tăng i sau
  • Performance: ++i thường nhanh hơn với objects
  • For loops: Prefer ++i

Q: Khi nào dùng const?

A:

cpp
const int x = 42;           // Constant variable
const int* ptr;             // Pointer to constant int
int* const ptr2;            // Constant pointer to int
const int* const ptr3;      // Constant pointer to constant int

void func(const string& s); // Const reference parameter
int getValue() const;       // Const member function

🏗 Object-Oriented Programming

Q: Constructor vs Destructor hoạt động như thế nào?

A:

cpp
class Example {
public:
    Example() { cout << "Constructor called\n"; }
    ~Example() { cout << "Destructor called\n"; }
};

// Constructor gọi khi tạo object
// Destructor gọi khi object bị destroy

Q: Khi nào cần virtual destructor?

A: Khi có inheritance và có thể delete qua base pointer:

cpp
class Base {
public:
    virtual ~Base() {}  // Virtual destructor cần thiết
};

class Derived : public Base {
    // ...
};

Base* ptr = new Derived();
delete ptr;  // Sẽ gọi đúng destructor

Q: Public vs Private vs Protected?

A:

  • Public: Truy cập được từ mọi nơi
  • Private: Chỉ class đó truy cập được
  • Protected: Class đó và derived classes truy cập được

Q: Overloading vs Overriding khác gì?

A:

  • Overloading: Cùng tên hàm, khác parameters
  • Overriding: Derived class định nghĩa lại virtual function của base class

🔗 Pointers và Memory

Q: Khi nào dùng pointer, khi nào dùng reference?

A:

cpp
// Reference: Khi biết chắc object tồn tại
void func(const string& str);

// Pointer: Khi có thể null, cần thay đổi trỏ đến object khác
void func(string* str) {
    if (str != nullptr) {
        // use str
    }
}

Q: Memory leak là gì và cách tránh?

A:

cpp
// BAD: Memory leak
int* ptr = new int(42);
// Forget to delete ptr

// GOOD: RAII với smart pointer
unique_ptr<int> ptr = make_unique<int>(42);
// Tự động delete khi out of scope

Q: Smart pointers nào dùng khi nào?

A:

  • unique_ptr: Single ownership, most common
  • shared_ptr: Shared ownership, reference counting
  • weak_ptr: Break circular references với shared_ptr

📚 STL và Containers

Q: Vector vs Array vs List khi nào dùng?

A:

  • Array: Kích thước cố định, cần performance tối đa
  • Vector: Dynamic size, random access, most common
  • List: Frequent insertion/deletion in middle

Q: Map vs Unordered_map khác gì?

A:

MapUnordered_map
ImplementationRed-black treeHash table
OrderingSorted by keyNo ordering
ComplexityO(log n)O(1) average
MemoryLowerHigher

Q: Iterator invalidation là gì?

A: Khi container thay đổi, iterator có thể bị vô hiệu:

cpp
vector<int> vec = {1, 2, 3};
auto it = vec.begin();
vec.push_back(4);  // Có thể invalidate iterator
// Không an toàn: cout << *it;

⚠️ Lỗi thường gặp

Q: "Segmentation fault" là gì?

A: Truy cập memory không hợp lệ:

cpp
// Causes
int* ptr = nullptr;
*ptr = 42;  // Segfault

int arr[10];
arr[20] = 5;  // Out of bounds

delete ptr;
delete ptr;  // Double delete

Q: Compile error vs Runtime error?

A:

  • Compile error: Syntax sai, type mismatch, missing headers
  • Runtime error: Logic sai, null pointer, out of bounds

Q: "undefined reference" error?

A: Linker không tìm thấy implementation:

cpp
// header.h
void myFunction();

// Cần có file .cpp implement myFunction
// hoặc include đúng library

🚀 Performance và Best Practices

Q: Cách optimize C++ code?

A:

  1. Profile trước khi optimize
  2. Sử dụng const reference cho parameters
  3. Avoid unnecessary copying
  4. Use appropriate containers
  5. Enable compiler optimizations (-O2, -O3)

Q: RAII là gì?

A: Resource Acquisition Is Initialization:

cpp
class FileHandler {
    FILE* file;
public:
    FileHandler(const char* name) : file(fopen(name, "r")) {}
    ~FileHandler() { if(file) fclose(file); }
};
// File tự động đóng khi object destroy

Q: Exception safety là gì?

A:

  • Basic guarantee: Object remains valid after exception
  • Strong guarantee: Operation either succeeds or has no effect
  • No-throw guarantee: Operation never throws

🎯 Thực hành và Học tập

Q: Làm sao để debug C++ code?

A:

  1. Print debugging: cout statements
  2. Debugger: GDB, Visual Studio debugger
  3. Static analysis: cppcheck, clang-static-analyzer
  4. Valgrind: Memory error detection

Q: Resources để học C++ thêm?

A:

  • Books: "Effective C++", "C++ Primer"
  • Websites: cppreference.com, learncpp.com
  • Practice: LeetCode, HackerRank, Codeforces
  • Communities: Stack Overflow, Reddit r/cpp

Q: Cách transition từ C sang C++?

A:

  1. Học STL containers thay vì C arrays
  2. Sử dụng string thay vì char arrays
  3. Học OOP concepts
  4. Sử dụng references thay vì pointers khi có thể
  5. Exception handling thay vì error codes

🔧 Tools và Environment

Q: IDE nào tốt cho C++?

A:

  • Beginner: Code::Blocks, Dev-C++
  • Professional: Visual Studio, CLion, Qt Creator
  • Cross-platform: VS Code với C++ extension

Q: Compiler nào nên dùng?

A:

  • Windows: MSVC, MinGW-w64
  • Linux: GCC, Clang
  • macOS: Clang (Xcode Command Line Tools)

Q: CMake là gì và có cần học không?

A: Build system để manage large C++ projects. Không bắt buộc cho beginner nhưng hữu ích cho dự án lớn.

Khóa học C++ miễn phí