> For the complete documentation index, see [llms.txt](https://42-guide.gitbook.io/42-guide/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://42-guide.gitbook.io/42-guide/all-about-c++/classes-and-objects.md).

# Classes and Objects

Classes and objects are the foundation of **object-oriented programming (OOP)**. Let’s break it down step-by-step with examples.

***

#### **1. What Are Classes and Objects?**

* **Class**: A blueprint or template for creating objects. It defines **data (attributes)** and **functions (methods)**.
* **Object**: An **instance** of a class. Think of a class as a cookie cutter and objects as the cookies.

**Example**:

```cpp
// Define a class
class Car {
public:    // Public members (accessible outside the class)
    string brand;
    void honk() { cout << "Beep! Beep!" << endl; }

private:   // Private members (accessible only inside the class)
    int mileage;
};
```

***

#### **2. Public vs. Private Members**

* **Public**: Accessible from **anywhere** (e.g., `brand` and `honk()` above).
* **Private**: Accessible **only inside the class** (e.g., `mileage`). Use getters/setters to access/modify them safely.

**Why Private Members?**

* **Encapsulation**: Protect data from unintended changes.
* Control how data is accessed (e.g., validate input before setting a value).

**Example**:

```cpp
class BankAccount {
private:
    double balance;

public:
    // Setter (to modify private member)
    void deposit(double amount) {
        if (amount > 0) balance += amount;
    }

    // Getter (to read private member)
    double getBalance() { return balance; }
};
```

***

#### **3. Member Functions (Methods)**

Functions defined inside a class to operate on its data.

**Example**:

```cpp
class Rectangle {
private:
    int width, height;

public:
    // Setter method
    void setDimensions(int w, int h) {
        width = w;
        height = h;
    }

    // Member function to calculate area
    int calculateArea() {
        return width * height;
    }
};
```

***

#### **4. Constructors and Destructors**

* **Constructor**: Special function called when an object is created. Initializes data members.
* **Destructor**: Called when an object is destroyed. Use it to clean up resources (e.g., memory).

**Example**:

```cpp
class Student {
private:
    string name;
    int age;

public:
    // Constructor (same name as the class)
    Student(string n, int a) {
        name = n;
        age = a;
    }

    // Destructor (~ClassName)
    ~Student() {
        cout << "Student object destroyed!" << endl;
    }
};

int main() {
    Student s1("Alice", 20); // Constructor called here
    return 0; // Destructor called automatically when s1 goes out of scope
}
```

***

#### **5. Full Example**

```cpp
#include <iostream>
using namespace std;

class Dog {
private:
    string name;
    int age;

public:
    // Constructor
    Dog(string n, int a) : name(n), age(a) {}

    // Public method to access private data
    void bark() {
        cout << name << " says Woof! (Age: " << age << ")" << endl;
    }

    // Setter for age
    void setAge(int a) {
        if (a > 0) age = a;
    }
};

int main() {
    Dog myDog("Buddy", 3);
    myDog.bark(); // Output: Buddy says Woof! (Age: 3)
    myDog.setAge(4);
    myDog.bark(); // Output: Buddy says Woof! (Age: 4)
    return 0;
}
```

***

#### **6. Best Practices**

1. **Encapsulate Data**: Keep data members `private` and use getters/setters.
2. **Use Constructors**: Initialize all data members to avoid garbage values.
3. **Avoid Public Variables**: Unless they’re constants (`const`).
4. **Separate Declaration/Definition**: Declare classes in `.h` (header) files and define methods in `.cpp` files.

***

#### **7. Common Mistakes**

**Mistake 1**: Accessing private members directly.

```cpp
Dog myDog("Buddy", 3);
myDog.age = 4; // Error: 'age' is private!
```

**Fix**: Use a setter:

```cpp
myDog.setAge(4); // Valid
```

**Mistake 2**: Forgetting the semicolon `;` after a class definition.

```cpp
class Dog { ... } // Missing ;
```

***

#### **8. Where to Learn More**

* **Books**:
  * *C++ Primer* (Chapter 7: Classes)
  * *Effective C++* by Scott Meyers (Item 22: Declare data members private)
* **Websites**:
  * [LearnCpp.com - Classes](https://www.learncpp.com/cpp-tutorial/classes-and-class-members/)
  * [cppreference.com - Classes](https://en.cppreference.com/w/cpp/language/class)
  * [GeeksforGeeks - C++ Classes](https://www.geeksforgeeks.org/c-classes-and-objects/)
* **Courses**:
  * [C++ For Programmers (Coursera)](https://www.coursera.org/learn/c-plus-plus-a)

***

#### **Key Takeaway**

* Classes define **what an object is** (data + behavior).
* Objects are **instances** of classes.
* Use `public` for methods that need external access and `private` for data protection.
* Constructors initialize objects, and destructors clean up resources.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://42-guide.gitbook.io/42-guide/all-about-c++/classes-and-objects.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
