In this section, we will delve into the core concepts of Object-Oriented Programming (OOP) in C++: classes and objects. Understanding these concepts is crucial for writing modular, reusable, and maintainable code.
Key Concepts
- Class: A blueprint for creating objects. It defines a datatype by bundling data and methods that work on the data into one single unit.
- Object: An instance of a class. When a class is defined, no memory is allocated until an object of that class is created.
- Member Variables: Variables defined inside a class.
- Member Functions: Functions defined inside a class.
Defining a Class
A class is defined using the class keyword followed by the class name and a pair of curly braces {}. Inside the curly braces, you define member variables and member functions.
class Car {
public:
// Member Variables
string brand;
string model;
int year;
// Member Functions
void displayInfo() {
cout << "Brand: " << brand << ", Model: " << model << ", Year: " << year << endl;
}
};Explanation
-
Access Specifiers:
public,private, andprotectedare access specifiers. They define the access level of the members of the class.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.
-
Member Variables:
brand,model, andyearare member variables of the classCar. -
Member Functions:
displayInfo()is a member function that prints the car's information.
Creating Objects
To create an object of a class, you simply declare a variable of the class type.
int main() {
Car car1; // Create an object of Car
// Accessing and modifying member variables
car1.brand = "Toyota";
car1.model = "Corolla";
car1.year = 2020;
// Calling member function
car1.displayInfo();
return 0;
}Explanation
Car car1;creates an objectcar1of the classCar.car1.brand = "Toyota";assigns the value "Toyota" to thebrandmember variable ofcar1.car1.displayInfo();calls thedisplayInfomember function ofcar1.
Practical Example
Let's create a more comprehensive example with multiple member functions and private member variables.
#include <iostream>
using namespace std;
class BankAccount {
private:
string accountNumber;
double balance;
public:
// Constructor
BankAccount(string accNum, double initialBalance) {
accountNumber = accNum;
balance = initialBalance;
}
// Member Functions
void deposit(double amount) {
balance += amount;
cout << "Deposited: $" << amount << endl;
}
void withdraw(double amount) {
if (amount <= balance) {
balance -= amount;
cout << "Withdrew: $" << amount << endl;
} else {
cout << "Insufficient balance!" << endl;
}
}
void displayBalance() {
cout << "Account Number: " << accountNumber << ", Balance: $" << balance << endl;
}
};
int main() {
// Create an object of BankAccount
BankAccount account1("123456789", 1000.0);
// Perform operations
account1.deposit(500.0);
account1.withdraw(200.0);
account1.displayBalance();
return 0;
}Explanation
- Constructor:
BankAccount(string accNum, double initialBalance)initializes the member variablesaccountNumberandbalance. - Member Functions:
deposit,withdraw, anddisplayBalanceperform operations on thebalanceand display the account information.
Exercises
Exercise 1: Define a Class
Define a class Student with the following member variables and functions:
- Member Variables:
name,age,grade - Member Functions:
setDetails,getDetails
#include <iostream>
using namespace std;
class Student {
public:
string name;
int age;
char grade;
void setDetails(string n, int a, char g) {
name = n;
age = a;
grade = g;
}
void getDetails() {
cout << "Name: " << name << ", Age: " << age << ", Grade: " << grade << endl;
}
};
int main() {
Student student1;
student1.setDetails("John Doe", 20, 'A');
student1.getDetails();
return 0;
}Exercise 2: Private Members
Modify the Student class to make name, age, and grade private. Add public member functions to set and get these values.
#include <iostream>
using namespace std;
class Student {
private:
string name;
int age;
char grade;
public:
void setDetails(string n, int a, char g) {
name = n;
age = a;
grade = g;
}
void getDetails() {
cout << "Name: " << name << ", Age: " << age << ", Grade: " << grade << endl;
}
};
int main() {
Student student1;
student1.setDetails("John Doe", 20, 'A');
student1.getDetails();
return 0;
}Common Mistakes and Tips
- Access Specifiers: Ensure you understand the difference between
public,private, andprotected. Useprivatefor member variables to enforce encapsulation. - Initialization: Always initialize member variables, either through constructors or directly.
- Object Creation: Remember that creating an object of a class allocates memory for the member variables.
Conclusion
In this section, we covered the basics of classes and objects in C++. We learned how to define a class, create objects, and use member variables and functions. These concepts form the foundation of Object-Oriented Programming and are essential for writing structured and efficient C++ code. In the next section, we will explore constructors and destructors, which are special member functions used for initializing and cleaning up objects.
C++ Programming Course
Module 1: Introduction to C++
- Introduction to C++
- Setting Up the Development Environment
- Basic Syntax and Structure
- Variables and Data Types
- Input and Output
Module 2: Control Structures
Module 3: Functions
Module 4: Arrays and Strings
Module 5: Pointers and References
- Introduction to Pointers
- Pointer Arithmetic
- Pointers and Arrays
- References
- Dynamic Memory Allocation
Module 6: Object-Oriented Programming
- Introduction to OOP
- Classes and Objects
- Constructors and Destructors
- Inheritance
- Polymorphism
- Encapsulation and Abstraction
Module 7: Advanced Topics
- Templates
- Exception Handling
- File I/O
- Standard Template Library (STL)
- Lambda Expressions
- Multithreading
