C++ Classes and Objects: Constructors, Access Control, and Destructors

C++ Classes and Objects: Constructors, Access Control, and Destructors

이 글의 핵심

Learn C++ classes and objects: members, constructors, access control, destructors for RAII, and common beginner mistakes like missing semicolons after class definitions.

Class as blueprint

Analogy: the class is a mold; objects are the things you stamp out—many instances from one definition.

class = blueprint (define once)
object = instance (you can create many)

First class

#include <iostream>
#include <string>
using namespace std;

class Person {
public:
    string name;
    int age;
    
    void introduce() {
        cout << "Hello, I'm " << name << ", " << age << " years old." << endl;
    }
};

int main() {
    Person p1;
    p1.name = "Alice";
    p1.age = 25;
    p1.introduce();
    return 0;
}

Constructors

Default and parameterized constructors initialize objects; use member initializer lists for efficiency.

Access control

private data with public methods is the standard encapsulation pattern (e.g., BankAccount with deposit/withdraw/getBalance).

Destructors

Release resources acquired in the constructor—paired RAII logic.

Frequent mistakes

  • Constructor name must match the class exactly.
  • Cannot access private members outside the class.
  • Class definitions end with }; — the semicolon is required.

Practical examples

The Korean article includes Student grades, a simple Character battle, and Book/Library—the same patterns apply: private fields, public behavior, invariants (HP bounds, valid scores).

Shallow vs deep copy

If a class owns raw pointers, default copy can double-free. Implement copy/move operations or use smart pointers / Rule of Zero.

const member functions

Getters that do not mutate should be const so they work on const objects.

Performance section (summary)

Prefer appropriate containers, pass by const& for large inputs, measure before optimizing.

FAQ

Beginner-friendly; real projects use classes constantly; C++ emphasizes performance and control.


  • Functions
  • Inheritance
  • Design patterns

Practical tips

Debugging

  • Warnings first.

Performance

  • Profile; pick data structures by complexity.

Code review

  • Conventions and invariants documented.

Practical checklist

Before coding

  • Is a class the right boundary?

While coding

  • Members initialized?

During review

  • Copy policy explicit?

C++, class, object, OOP, beginner