In C++, classes and objects are the fundamental building blocks of object-oriented programming (OOP).
A class is a blueprint for creating objects, which are instances of that class.
Classes encapsulate data and functions that operate on that data, supporting modular and reusable code.
1. Defining a Class and Creating an Object
A class is defined using the class keyword, followed by the class name and a set of curly braces {} containing member variables and member functions.
Example: Defining a Basic Class
#include <iostream> using namespace std; class Car { public: string make; string model; int year; void displayInfo() { cout << "Make: " << make << ", Model: " << model << ", Year: " << year << endl; } }; int main() { Car car1; // Creating an object of the Car class car1.make = "Toyota"; car1.model = "Camry"; car1.year = 2020; car1.displayInfo(); // Calling a member function return 0; }
Explanation:
- Car is a class with three member variables: make, model, and year, and a member function displayInfo.
- car1 is an object (instance) of the Car class, and car1.displayInfo() displays its information.
Output:
Make: Toyota, Model: Camry, Year: 2020
2. Private and Public Access Specifiers
In C++, class members can have different levels of access:
- Public members are accessible from outside the class.
- Private members are accessible only within the class and cannot be accessed directly by objects.
#include <iostream> using namespace std; class BankAccount { private: double balance; // Private member variable public: void setBalance(double amount) { balance = amount; } double getBalance() { return balance; } }; int main() { BankAccount account; account.setBalance(500.0); // Sets balance using a public method cout << "Balance: $" << account.getBalance() << endl; return 0; }
Explanation:
- balance is private and can’t be accessed directly. setBalance and getBalance are public methods used to set and get the balance.
Output:
Balance: $500
3. Constructors
A constructor is a special member function that initializes objects when they are created.
Constructors have the same name as the class and no return type.
Example: Using a Constructor
#include <iostream> using namespace std; class Car { public: string make; string model; int year; // Constructor Car(string m, string mo, int y) { make = m; model = mo; year = y; } void displayInfo() { cout << "Make: " << make << ", Model: " << model << ", Year: " << year << endl; } }; int main() { Car car1("Toyota", "Camry", 2020); car1.displayInfo(); return 0; }
Explanation:
- The constructor Car(string m, string mo, int y) initializes make, model, and year.
- car1 is created and initialized in one line: Car car1(“Toyota”, “Camry”, 2020);.
Output:
Make: Toyota, Model: Camry, Year: 2020
4. Default Constructor
If no constructor is provided, C++ provides a default constructor with no parameters.
However, you can also define your own default constructor.
#include <iostream> using namespace std; class Car { public: string make; string model; int year; // Default Constructor Car() { make = "Unknown"; model = "Unknown"; year = 0; } void displayInfo() { cout << "Make: " << make << ", Model: " << model << ", Year: " << year << endl; } }; int main() { Car car1; car1.displayInfo(); return 0; }
Explanation:
- The default constructor initializes make, model, and year with default values.
Output:
Make: Unknown, Model: Unknown, Year: 0
5. Parameterized Constructor
A parameterized constructor takes arguments to initialize the object with specific values.
#include <iostream> using namespace std; class Book { public: string title; string author; double price; // Parameterized Constructor Book(string t, string a, double p) { title = t; author = a; price = p; } void displayInfo() { cout << "Title: " << title << ", Author: " << author << ", Price: $" << price << endl; } }; int main() { Book book1("1984", "George Orwell", 9.99); book1.displayInfo(); return 0; }
Explanation:
- The Book constructor initializes title, author, and price with specific values.
Output:
Title: 1984, Author: George Orwell, Price: $9.99
6. Destructor
A destructor is a special member function that is called when an object is destroyed.
It has the same name as the class, preceded by a tilde (~), and no parameters.
#include <iostream> using namespace std; class Car { public: Car() { cout << "Constructor called!" << endl; } ~Car() { cout << "Destructor called!" << endl; } }; int main() { Car car1; cout << "Main function" << endl; return 0; }
Explanation:
- The destructor ~Car() is called automatically when car1 goes out of scope.
Output:
Constructor called! Main function Destructor called!
7. Member Functions Outside the Class
Member functions can be defined outside the class using the scope resolution operator (::).
#include <iostream> using namespace std; class Rectangle { private: int length; int width; public: Rectangle(int l, int w); int area(); }; // Constructor definition outside the class Rectangle::Rectangle(int l, int w) { length = l; width = w; } // Member function definition outside the class int Rectangle::area() { return length * width; } int main() { Rectangle rect(5, 3); cout << "Area: " << rect.area() << endl; return 0; }
Explanation:
- Rectangle::Rectangle and Rectangle::area define the constructor and area function outside the class.
Output:
Area: 15
8. this Pointer
The this pointer refers to the current instance of the class.
It’s useful when a member function’s parameters have the same names as member variables.
#include <iostream> using namespace std; class Car { public: string make; string model; Car(string make, string model) { this->make = make; this->model = model; } void displayInfo() { cout << "Make: " << make << ", Model: " << model << endl; } }; int main() { Car car1("Toyota", "Corolla"); car1.displayInfo(); return 0; }
Explanation:
- The this pointer differentiates between the parameter make and the member variable make.
Output:
Make: Toyota, Model: Corolla
9. Constant Member Functions
A constant member function does not modify any member variables.
It’s defined with the const keyword after the parameter list.
#include <iostream> using namespace std; class Circle { private: double radius; public: Circle(double r) : radius(r) {} double getRadius() const { return radius; } }; int main() { Circle circle(5.5); cout << "Radius: " << circle.getRadius() << endl; return 0; }
Explanation:
- getRadius is a const member function that cannot modify any member variables.
Output:
Radius: 5.5
10. Summary Table
Feature | Description |
---|---|
Defining a class | Use class ClassName { … }; to define a class |
Public and private access | Public members accessible outside, private only inside the class |
Constructor | Special function to initialize objects |
Default constructor | Constructor with no parameters |
Parameterized constructor | Constructor with parameters to set initial values |
Destructor | Special function to clean up when object goes out of scope (~ClassName()) |
Scope resolution | Define functions outside the class with ClassName::functionName |
this pointer | Refers to the current object instance |
Constant member functions | const functions that do not modify member variables |
Complete Example: Class with Various Features
This example demonstrates defining a class with a constructor, destructor, private and public members, and member functions.
#include <iostream> using namespace std; class BankAccount { private: string owner; double balance; public: BankAccount(string o, double b) : owner(o), balance(b) { cout << "Account created for " << owner << endl; } ~BankAccount() { cout << "Account closed for " << owner << endl; } void deposit(double amount) { balance += amount; cout << "$" << amount << " deposited. New balance: $" << balance << endl; } void withdraw(double amount) { if (amount <= balance) { balance -= amount; cout << "$" << amount << " withdrawn. New balance: $" << balance << endl; } else { cout << "Insufficient balance." << endl; } } double getBalance() const { return balance; } }; int main() { BankAccount account("Alice", 1000); account.deposit(500); account.withdraw(200); cout << "Final balance: $" << account.getBalance() << endl; return 0; }
Explanation:
- BankAccount has a constructor that initializes owner and balance.
- deposit and withdraw are public methods to interact with balance.
- The destructor prints a message when the BankAccount object is destroyed.
Sample Output:
Account created for Alice $500 deposited. New balance: $1500 $200 withdrawn. New balance: $1300 Final balance: $1300 Account closed for Alice
This tutorial covers the basics of classes and objects in C++.