Class in C++

 


A class in C++ is a user-defined data type that allows you to group variables (data members) and functions (member functions) together into a single unit. It is the foundation of Object-Oriented Programming (OOP).


1️⃣ Why Use Classes?

✅ Encapsulation – Groups related data and functions together.
✅ Reusability – Can be used to create multiple objects with the same properties.
✅ Modularity – Helps organize code efficiently.
✅ Abstraction – Hides unnecessary details from the user.


2️⃣ Defining a Class in C++

Syntax:

class ClassName {
  private:
      // Private data members (hidden from outside)
  public:
      // Public member functions (accessible outside)
};

3️⃣ Example: Creating a Class and Object

#include <iostream>
using namespace std;

class Car {
public:
    string brand;
    int year;

    void displayInfo() {
        cout << "Brand: " << brand << ", Year: " << year << endl;
    }
};

int main() {
    Car car1;  // Creating an object
    car1.brand = "Toyota";
    car1.year = 2022;
    
    car1.displayInfo();  // Calling a function

    return 0;
}

Output:

Brand: Toyota, Year: 2022

Explanation:

  • Car is a class with two variables (brand and year) and a function (displayInfo()).
  • car1 is an object of class Car.

4️⃣ Access Specifiers in Classes

C++ has three access specifiers:

Access Specifier Description
public Accessible from anywhere.
private Accessible only within the class.
protected Similar to private, but accessible in derived (child) classes.
class Example {
private:
    int secretNumber;  // Cannot be accessed outside
public:
    int number;  // Can be accessed outside
};

5️⃣ Using Private Members in a Class

To access private variables, we use getter and setter methods.

#include <iostream>
using namespace std;

class BankAccount {
private:
    double balance;

public:
    void setBalance(double b) {
        if (b >= 0)
            balance = b;
    }

    double getBalance() {
        return balance;
    }
};

int main() {
    BankAccount account;
    account.setBalance(1000);  // Setting private data
    cout << "Balance: $" << account.getBalance() << endl;

    return 0;
}

Output:

Balance: $1000
  • The balance variable is private, so we cannot access it directly.
  • setBalance() and getBalance() allow controlled access to balance.

6️⃣ Constructor in a Class

A constructor is a special function that is automatically called when an object is created.

#include <iostream>
using namespace std;

class Student {
public:
    string name;
    int age;

    // Constructor
    Student(string n, int a) {
        name = n;
        age = a;
    }

    void display() {
        cout << "Name: " << name << ", Age: " << age << endl;
    }
};

int main() {
    Student s1("John", 21);
    s1.display();
    return 0;
}

Output:

Name: John, Age: 21

7️⃣ Destructor in a Class

A destructor is a special function that is automatically called when an object is destroyed.

class Example {
public:
    Example() {
        cout << "Constructor Called!" << endl;
    }
    ~Example() {
        cout << "Destructor Called!" << endl;
    }
};

int main() {
    Example obj;
    return 0;
}

Output:

Constructor Called!
Destructor Called!
  • The destructor ~Example() is called automatically when obj goes out of scope.

8️⃣ Example: Real-World Class - Employee System

#include <iostream>
using namespace std;

class Employee {
private:
    int empID;
    double salary;

public:
    Employee(int id, double sal) {
        empID = id;
        salary = sal;
    }

    void showDetails() {
        cout << "Employee ID: " << empID << ", Salary: $" << salary << endl;
    }
};

int main() {
    Employee e1(101, 50000);
    Employee e2(102, 60000);

    e1.showDetails();
    e2.showDetails();

    return 0;
}

Output:

Employee ID: 101, Salary: $50000
Employee ID: 102, Salary: $60000

9️⃣ Summary

✅ Classes help organize code by grouping data and functions together.
✅ Access specifiers (private, public, protected) control visibility.
✅ Encapsulation hides data from direct access, improving security.
✅ Constructors and destructors help in automatic initialization and cleanup.

Would you like to learn inheritance (how classes can be extended) next? 🚀

Post a Comment

0 Comments