C++ Basic Programs Using Class

6 min read Jul 01, 2024
C++ Basic Programs Using Class

C++ Basic Programs Using Class

Classes are fundamental building blocks in object-oriented programming (OOP) languages like C++. They encapsulate data (member variables) and functions (member functions) that operate on that data. This structure allows for modularity, reusability, and data protection.

Here's a breakdown of basic C++ programs using classes, illustrating their key concepts:

1. Simple Class Example: Representing a Student

#include 
#include 

using namespace std;

// Defining the Student class
class Student {
private:
  string name;
  int rollNumber;
  float marks;

public:
  // Constructor to initialize student details
  Student(string s, int r, float m) {
    name = s;
    rollNumber = r;
    marks = m;
  }

  // Member function to display student information
  void displayDetails() {
    cout << "Name: " << name << endl;
    cout << "Roll Number: " << rollNumber << endl;
    cout << "Marks: " << marks << endl;
  }
};

int main() {
  // Creating an object of the Student class
  Student student1("John Doe", 101, 85.5);

  // Accessing and displaying student details
  student1.displayDetails();

  return 0;
}

Explanation:

  • Class Definition: The class Student defines a blueprint for creating student objects.
  • Private Members: The private section enforces data hiding, making name, rollNumber, and marks accessible only within the class itself.
  • Constructor: The Student constructor initializes the member variables when a Student object is created.
  • Public Member Function: displayDetails allows external code to access and display the student's information.
  • Object Creation: Student student1("John Doe", 101, 85.5); creates an object named student1 with specified details.

2. Class with Methods for Calculation

#include 

using namespace std;

// Defining the Rectangle class
class Rectangle {
private:
  int length;
  int width;

public:
  // Constructor to initialize length and width
  Rectangle(int l, int w) {
    length = l;
    width = w;
  }

  // Member function to calculate area
  int calculateArea() {
    return length * width;
  }

  // Member function to calculate perimeter
  int calculatePerimeter() {
    return 2 * (length + width);
  }
};

int main() {
  // Creating a Rectangle object
  Rectangle rect(5, 3);

  // Calculating and displaying area and perimeter
  cout << "Area: " << rect.calculateArea() << endl;
  cout << "Perimeter: " << rect.calculatePerimeter() << endl;

  return 0;
}

Explanation:

  • Class with Methods: The Rectangle class includes calculateArea and calculatePerimeter member functions that perform operations on the object's data (length and width).
  • Method Calls: The rect.calculateArea() and rect.calculatePerimeter() calls access the methods of the rect object.

3. Class with Encapsulation and Data Validation

#include 

using namespace std;

// Defining the BankAccount class
class BankAccount {
private:
  int accountNumber;
  double balance;

public:
  // Constructor to initialize account number and balance
  BankAccount(int accNo, double initialBalance) {
    accountNumber = accNo;
    balance = initialBalance;
  }

  // Member function to deposit money
  void deposit(double amount) {
    if (amount > 0) {
      balance += amount;
      cout << "Deposit successful. New balance: " << balance << endl;
    } else {
      cout << "Invalid deposit amount." << endl;
    }
  }

  // Member function to withdraw money
  void withdraw(double amount) {
    if (amount > 0 && amount <= balance) {
      balance -= amount;
      cout << "Withdrawal successful. New balance: " << balance << endl;
    } else {
      cout << "Invalid withdrawal amount or insufficient balance." << endl;
    }
  }

  // Member function to display account information
  void displayAccountDetails() {
    cout << "Account Number: " << accountNumber << endl;
    cout << "Balance: " << balance << endl;
  }
};

int main() {
  // Creating a BankAccount object
  BankAccount account1(12345, 1000.0);

  // Performing operations on the account
  account1.deposit(500.0);
  account1.withdraw(200.0);
  account1.displayAccountDetails();

  return 0;
}

Explanation:

  • Encapsulation: The BankAccount class encapsulates account data (accountNumber and balance) and methods that operate on them.
  • Data Validation: The deposit and withdraw methods include validation logic to ensure valid transactions (e.g., positive deposit amount, sufficient balance for withdrawal).
  • Method Access: The account1.deposit(500.0) and account1.withdraw(200.0) calls invoke the respective methods on the account1 object.

These are just simple examples to get you started with classes in C++. As you delve deeper into OOP concepts, you'll explore more advanced topics like inheritance, polymorphism, and abstract classes, which further enhance the power and flexibility of classes in C++.

Latest Posts