Skip to Content
ClassesC++ Classes and Object-Oriented Programming

C++ Classes and Object-Oriented Programming

Classes are the foundation of Object-Oriented Programming (OOP) in C++. They allow you to create user-defined data types that bundle data and functions together.

What is a Class?

A class is a blueprint for creating objects. It defines a data structure that combines data (member variables) and functions (member functions/methods) that operate on that data.

Basic Class Syntax

class ClassName { public: // Public members (accessible from outside) int publicVariable; void publicMethod(); private: // Private members (only accessible within the class) int privateVariable; void privateMethod(); protected: // Protected members (accessible in derived classes) int protectedVariable; };

Simple Class Example

#include <iostream> #include <string> using namespace std; class Car { public: string brand; string model; int year; void displayInfo() { cout << year << " " << brand << " " << model << endl; } }; int main() { Car car1; car1.brand = "Toyota"; car1.model = "Camry"; car1.year = 2023; car1.displayInfo(); return 0; }

Output:

2023 Toyota Camry

Creating Objects

An object is an instance of a class:

Car myCar; // Create an object of Car Car yourCar; // Create another object of Car

Accessing Class Members

Use the dot operator (.) to access members:

myCar.brand = "Honda"; myCar.displayInfo();

Access Specifiers

C++ has three access specifiers:

Public

Members are accessible from anywhere:

class MyClass { public: int publicVar; };

Private

Members are only accessible within the class (default):

class MyClass { private: int privateVar; };

Protected

Members are accessible in the class and its derived classes:

class MyClass { protected: int protectedVar; };

Topics in This Section

Explore Object-Oriented Programming concepts:

  • OOPs Concepts: Learn the four pillars of OOP - Encapsulation, Abstraction, Inheritance, and Polymorphism
  • Constructor: Understand how to initialize objects with constructors
  • Inheritance: Learn how to create new classes from existing ones

Encapsulation Example

Encapsulation is about bundling data and methods together and controlling access:

#include <iostream> using namespace std; class BankAccount { private: double balance; public: BankAccount() { balance = 0; } void deposit(double amount) { if (amount > 0) { balance += amount; cout << "Deposited: $" << amount << endl; } } void withdraw(double amount) { if (amount > 0 && amount <= balance) { balance -= amount; cout << "Withdrawn: $" << amount << endl; } else { cout << "Insufficient funds!" << endl; } } double getBalance() { return balance; } }; int main() { BankAccount account; account.deposit(1000); account.withdraw(500); cout << "Balance: $" << account.getBalance() << endl; return 0; }

Output:

Deposited: $1000 Withdrawn: $500 Balance: $500

Member Functions

Functions defined inside a class can be:

Defined Inside the Class

class MyClass { public: void display() { cout << "Hello!" << endl; } };

Defined Outside the Class

class MyClass { public: void display(); }; void MyClass::display() { cout << "Hello!" << endl; }

Benefits of Classes

  1. Encapsulation: Bundle data and methods together
  2. Data Hiding: Control access to data through public methods
  3. Reusability: Create multiple objects from the same class
  4. Modularity: Organize code into logical units
  5. Maintainability: Easier to modify and debug

Real-World Example: Student Class

#include <iostream> #include <string> using namespace std; class Student { private: string name; int rollNumber; double marks; public: void setData(string n, int r, double m) { name = n; rollNumber = r; marks = m; } void display() { cout << "Name: " << name << endl; cout << "Roll Number: " << rollNumber << endl; cout << "Marks: " << marks << endl; } double getMarks() { return marks; } }; int main() { Student student1; student1.setData("Alice", 101, 95.5); student1.display(); return 0; }

Output:

Name: Alice Roll Number: 101 Marks: 95.5

Class vs Struct

In C++, the main difference is:

  • class: Members are private by default
  • struct: Members are public by default
class MyClass { int x; // private by default }; struct MyStruct { int x; // public by default };

Best Practices

  1. Use meaningful names: class Car is better than class C
  2. Keep data private: Use getter/setter methods for access
  3. Single Responsibility: Each class should have one clear purpose
  4. Use const methods: Mark methods that don’t modify data as const
  5. Initialize members: Always initialize member variables

Example with Const Method

class Rectangle { private: double length; double width; public: Rectangle(double l, double w) : length(l), width(w) {} double getArea() const { // const method return length * width; } double getPerimeter() const { return 2 * (length + width); } };

Classes are the cornerstone of modern C++ programming. Master them to write better, more organized code!

Last updated on