C++ Object-Oriented Programming: Classes, Objects, and Encapsulation
Defining Classes and Objects
In C++, the class acts as a blueprint for creating objects, encapsulating data (attributes) and functions (methods) into a single unit. An object is an instance of a class, allocated in memory with a specific state. By defining classes, programmers can create abstract data types that model real-world entities.
Access Specifiers and Class Structure
Classes define access levels for their members using specifiers like public, private, and protected. Public members are accessible from outside the class, while private members can only be accessed by member functions or friends of the class, ensuring data hiding and integrity.
class Product {
public:
double getPrice() {
return cost;
}
void setCost(double c) {
cost = c;
}
private:
double cost;
int stockId;
};
Constructors and Destructors
A constructor is a special member function automatically called when an object is created, used to initialize data members. Conversely, a destructor is invoked when an object is destroyed, typically used to release resources. Both functions share the class name, with the destructor preceded by a tilde (~).
Example 1: Library Management System
This example demonstrates a class representing a library member. It includes logic to limit the number of borrowed items, illustrating how objects manage their own state.
#include <iostream>
#include <string>
using namespace std;
class LibraryMember {
private:
string memberId;
string fullName;
int borrowedItems;
public:
// Parameterized constructor
LibraryMember(string id, string name, int items)
: memberId(id), fullName(name), borrowedItems(items) {}
// Default constructor
LibraryMember() : borrowedItems(0) {}
void displayStatus() {
cout << "ID: " << memberId << ", Name: " << fullName
<< ", Items: " << borrowedItems << endl;
}
bool checkoutItem() {
if (borrowedItems >= 10) {
return false;
}
borrowedItems++;
return true;
}
};
void processCheckout(LibraryMember &member) {
if (!member.checkoutItem()) {
member.displayStatus();
cout << "Checkout limit reached (10 items)." << endl;
} else {
cout << "Checkout successful." << endl;
member.displayStatus();
}
}
int main() {
LibraryMember m1("LIB-101", "Alice Smith", 10);
LibraryMember m2;
processCheckout(m1);
processCheckout(m2);
return 0;
}
Example 2: Time Logic Implementation
The following code defines a DigitalClock class. It handles the logic for incrementing time, correctly managing the overflow from seconds to minutes and minutes to hours.
#include <iostream>
using namespace std;
class DigitalClock {
private:
int hours;
int minutes;
int seconds;
public:
DigitalClock(int h, int m, int s) : hours(h), minutes(m), seconds(s) {}
DigitalClock() : hours(0), minutes(0), seconds(0) {}
void setTime(int h, int m, int s) {
hours = h;
minutes = m;
seconds = s;
}
void tick() {
seconds++;
if (seconds >= 60) {
seconds = 0;
minutes++;
}
if (minutes >= 60) {
minutes = 0;
hours++;
}
if (hours >= 24) {
hours = 0;
}
}
void printTime() const {
cout << hours << ":" << minutes << ":" << seconds << endl;
}
};
int main() {
DigitalClock timer(14, 59, 59);
timer.printTime(); // Output: 14:59:59
timer.tick();
timer.printTime(); // Output: 15:0:0
return 0;
}
Example 3: Friend Classes
C++ allows a class to grant another class access to its private members using the friend keyword. This example shows a SystemAdmin class that can access the private details of a UserProfile.
#include <iostream>
#include <string>
using namespace std;
class UserProfile; // Forward declaration
class SystemAdmin {
public:
void inspectProfile(UserProfile &user);
};
class UserProfile {
private:
friend class SystemAdmin; // Granting access
string username;
int securityLevel;
public:
UserProfile(string name, int level) : username(name), securityLevel(level) {}
void showPublicInfo() {
cout << "User: " << username << endl;
}
};
void SystemAdmin::inspectProfile(UserProfile &user) {
// Accessing private data directly
cout << "Admin Access - User: " << user.username
<< ", Level: " << user.securityLevel << endl;
}
int main() {
UserProfile u1("Dev_01", 5);
SystemAdmin admin;
u1.showPublicInfo(); // Public access
admin.inspectProfile(u1); // Friend access
return 0;
}