Introduction
In C++, classes and objects are fundamental concepts of Object-Oriented Programming (OOP). A class is a blueprint for creating objects, and an object is an instance of a class. Understanding classes and objects is essential for organizing and structuring your code in a modular, reusable, and maintainable way.
What is a Class?
A class is a user-defined data type that represents a blueprint for creating objects. It encapsulates data for the object and methods to manipulate that data. The class defines the attributes (data members) and behaviors (member functions or methods) that the objects created from the class will have.
Syntax for Defining a Class
class ClassName {
public:
// Data members (attributes)
dataType member1;
dataType member2;
// Member functions (methods)
returnType functionName(parameters) {
// Function body
}
};
Example: Defining a Class
#include <iostream>
using namespace std;
// Define a class named 'Person'
class Person {
public:
// Data members
string name;
int age;
// Member function to display person details
void display() {
cout << "Name: " << name << ", Age: " << age << endl;
}
};
Explanation
class Person
defines a class namedPerson
with data membersname
andage
, and a member functiondisplay()
.- The keyword
public
specifies that the members following it are accessible from outside the class.
What is an Object?
An object is an instance of a class. It represents a specific entity with attributes and behaviors defined by its class. Objects are created from classes and are used to access the data members and member functions defined in the class.
Example: Creating and Using an Object
#include <iostream>
using namespace std;
// Define a class named 'Person'
class Person {
public:
// Data members
string name;
int age;
// Member function to display person details
void display() {
cout << "Name: " << name << ", Age: " << age << endl;
}
};
int main() {
// Create an object of the Person class
Person person1;
// Initialize object members
person1.name = "John Doe";
person1.age = 30;
// Call the member function
person1.display();
return 0;
}
Output
Name: John Doe, Age: 30
Explanation
Person person1;
creates an objectperson1
of thePerson
class.- The object members are initialized using the dot operator (
.
). - The
display()
function is called to print the person’s details.
Access Specifiers
Access specifiers define the accessibility of the members of a class. The three most common access specifiers are:
public
: Members are accessible from outside the class.private
: Members are accessible only within the class.protected
: Members are accessible within the class and by derived class.
Example: Access Specifiers
#include <iostream>
using namespace std;
class Person {
private:
// Private data members
string name;
int age;
public:
// Public member function to set person details
void setDetails(string n, int a) {
name = n;
age = a;
}
// Public member function to display person details
void display() {
cout << "Name: " << name << ", Age: " << age << endl;
}
};
int main() {
Person person1;
// Set and display person details using public member functions
person1.setDetails("John Doe", 30);
person1.display();
return 0;
}
Output
Name: John Doe, Age: 30
Explanation
- The
name
andage
members are private and can only be accessed through public member functionssetDetails()
anddisplay()
.
Constructors
Constructors are special member functions that are automatically called when an object is created. They are used to initialize objects.
Example: Constructor
#include <iostream>
using namespace std;
class Person {
public:
string name;
int age;
// Constructor
Person(string n, int a) {
name = n;
age = a;
}
void display() {
cout << "Name: " << name << ", Age: " << age << endl;
}
};
int main() {
// Create an object using the constructor
Person person1("John Doe", 30);
// Call the member function
person1.display();
return 0;
}
Output
Name: John Doe, Age: 30
Explanation
Person(string n, int a)
is a constructor that initializes thename
andage
members.Person person1("John Doe", 30);
creates an objectperson1
using the constructor.
Destructors
Destructors are special member functions that are automatically called when an object is destroyed. They are used to perform cleanup tasks.
Example: Destructor
#include <iostream>
using namespace std;
class Person {
public:
string name;
int age;
// Constructor
Person(string n, int a) {
name = n;
age = a;
}
// Destructor
~Person() {
cout << "Destructor called for " << name << endl;
}
void display() {
cout << "Name: " << name << ", Age: " << age << endl;
}
};
int main() {
// Create an object using the constructor
Person person1("John Doe", 30);
// Call the member function
person1.display();
return 0;
}
Output
Name: John Doe, Age: 30
Destructor called for John Doe
Explanation
~Person()
is a destructor that prints a message when called.- The destructor is automatically called when
person1
goes out of scope.
Example Programs
Example 1: Bank Account Class
This example demonstrates creating a class to represent a bank account with deposit and withdrawal functionalities.
#include <iostream>
using namespace std;
class BankAccount {
private:
string accountHolder;
double balance;
public:
// Constructor
BankAccount(string holder, double initialBalance) {
accountHolder = holder;
balance = initialBalance;
}
// Member function to deposit money
void deposit(double amount) {
balance += amount;
}
// Member function to withdraw money
void withdraw(double amount) {
if (amount <= balance) {
balance -= amount;
} else {
cout << "Insufficient funds" << endl;
}
}
// Member function to display account details
void display() {
cout << "Account Holder: " << accountHolder << ", Balance: $" << balance << endl;
}
};
int main() {
// Create an object of the BankAccount class
BankAccount account("Alice", 1000.0);
// Perform operations on the account
account.display();
account.deposit(500.0);
account.display();
account.withdraw(200.0);
account.display();
account.withdraw(1500.0);
return 0;
}
Output
Account Holder: Alice, Balance: $1000
Account Holder: Alice, Balance: $1500
Account Holder: Alice, Balance: $1300
Insufficient funds
Explanation
- The
BankAccount
class represents a bank account withdeposit
andwithdraw
methods. - The
account
object is created using the constructor and various operations are performed on it.
Conclusion
Classes and objects are fundamental concepts in C++ that enable the creation of modular, reusable, and maintainable code. This chapter covered the definition of classes and objects, access specifiers, constructors, destructors, and provided example programs to demonstrate their usage. Understanding these concepts is essential for effective C++ programming.