Skip to main content

C++ Programming Practical Programs for Students | Call by Reference, Constructor Overloading and Account Class

C++ Programming Concepts and Object-Oriented Programming

Introduction
C++ is one of the most powerful and popular programming languages used in computer science and software development. It is an extension of the C programming language and supports both procedural programming and object-oriented programming (OOP). C++ is widely used for developing system software, application software, games, embedded systems, and many other types of programs because of its speed, flexibility, and efficiency.


Object-Oriented Programming is an important feature of C++. OOP helps programmers organize programs into objects and classes, making programs easier to manage, reuse, and understand. Some important concepts of OOP include classes, objects, constructors, encapsulation, inheritance, and polymorphism.


In this article, we will discuss three important C++ programming concepts:
Exchange of two variables using Call by Reference
Constructor Overloading in C++
Implementation of an Account Class with Deposit, Withdraw, Balance, and Interest Functions
These concepts are very useful for understanding the fundamentals of C++ programming and object-oriented programming.


1. Exchange of Two Variables Using Call by Reference
Introduction to Call by Reference
In C++, functions can receive arguments in different ways. One important method is Call by Reference. In this method, instead of sending copies of variables, the actual memory addresses or references of variables are passed to the function. Therefore, any changes made inside the function directly affect the original variables.


Call by Reference is useful because:
It avoids unnecessary copying of data.
It improves memory efficiency.
It allows functions to modify original values.
It is commonly used in swapping operations.
The symbol & is used to represent references in C++.
Objective of the Program
The objective of this program is:
To understand the concept of Call by Reference.

To exchange or swap the values of two variables.
To demonstrate how references work in C++.
Algorithm for Swapping Two Variables
Start the program.
Declare two variables.
Create a function with reference parameters.
Use a temporary variable for swapping.
Exchange the values.
Display the swapped values.
End the program.
C++ Program for Swapping Using Call by Reference
C++
#include <iostream>
using namespace std;

void swap(int &a, int &b)
{
    int temp;
    temp = a;
    a = b;
    b = temp;
}

int main()
{
    int x, y;

    cout << "Enter first number: ";
    cin >> x;
    cout << "Enter second number: ";
    cin >> y;

    cout << "Before swapping: ";
    cout << "x = " << x << " y = " << y << endl;

    swap(x, y);

    cout << "After swapping: ";
    cout << "x = " << x << " y = " << y << endl;

    return 0;
}
Explanation of the Program
In this program:
swap() function receives variables by reference.
temp temporarily stores one value.


Values are exchanged using assignment statements.
Since references are used, original values change directly.
For example:
If:
C++
x = 10
y = 20
After swapping:
C++
x = 20
y = 10
Advantages of Call by Reference
Faster execution
Saves memory
Allows direct modification
Useful for large programs


2. Constructor Overloading in C++
Introduction to Constructors
A constructor is a special member function in C++ that is automatically called when an object is created. The main purpose of a constructor is to initialize objects.
Characteristics of constructors:
Constructor name is same as class name.
Constructors have no return type.
Automatically executed during object creation.


There are different types of constructors:
Default Constructor
Parameterized Constructor
Copy Constructor
When multiple constructors are defined in the same class with different parameters, it is called Constructor Overloading.
Objective of Constructor Overloading
The objectives are:
To initialize objects in different ways.
To demonstrate polymorphism in constructors.
To improve flexibility in object creation.
Example of Constructor Overloading
Suppose we create a class called Student.
One constructor initializes default values.
Another constructor accepts student details.



This demonstrates constructor overloading.
C++ Program for Constructor Overloading
C++
#include <iostream>
using namespace std;

class Student
{
    int roll;
    string name;

public:

    // Default constructor
    Student()
    {
        roll = 0;
        name = "Unknown";
    }

    // Parameterized constructor
    Student(int r, string n)
    {
        roll = r;
        name = n;
    }

    void display()
    {
        cout << "Roll Number: " << roll << endl;
        cout << "Name: " << name << endl;
    }
};

int main()
{
    Student s1;
    Student s2(101, "Rahul");

    cout << "Student 1 Details:" << endl;
    s1.display();

    cout << endl;

    cout << "Student 2 Details:" << endl;
    s2.display();

    return 0;
}
Explanation of the Program
In this program:
Student() is a default constructor.
Student(int r, string n) is a parameterized constructor.

Both constructors have the same name but different parameters.
This is called constructor overloading.
Output Example
C++
Student 1 Details:
Roll Number: 0
Name: Unknown
Student 2 Details:
Roll Number: 101
Name: Rahul
Advantages of Constructor Overloading
Flexibility in object creation
Better code readability
Multiple initialization methods
Saves programming time
Real-Life Example
Constructor overloading can be compared to filling a form:
Sometimes complete information is available.
Sometimes only partial information is available.
Different constructors handle different situations.

3. Account Class Implementation in C++
Introduction to Classes and Objects
A class is a user-defined data type in C++ that contains data members and member functions.
An object is an instance of a class.
Classes help in:
Data security
Code reusability
Encapsulation
Organized programming
 systems commonly use classes for account management.
Objective of the Account Class Program
The objectives are:
To create a  account system.
To perform deposit and withdrawal operations.


To calculate interest.
To display account balance.
Features of the Account Class
The account class includes:
Account balance
Deposit function
Withdraw function
Show balance function
Compute interest function
C++ Program for Account Class
C++
#include <iostream>
using namespace std;

class Account
{
    float balance;
    float rate;

public:

    void initialize(float b, float r)
    {
        balance = b;
        rate = r;
    }

    void deposit(float amount)
    {
        balance = balance + amount;
        cout << "Amount Deposited Successfully" << endl;
    }

    void withdraw(float amount)
    {
        if(amount <= balance)
        {
            balance = balance - amount;
            cout << "Amount Withdrawn Successfully" << endl;
        }
        else
        {
            cout << "Insufficient Balance" << endl;
        }
    }

    void showBalance()
    {
        cout << "Current Balance: " << balance << endl;
    }

    void computeInterest()
    {
        float interest;

        interest = (balance * rate) / 100;

        cout << "Interest: " << interest << endl;
    }
};

int main()
{
    Account a1;

    a1.initialize(10000, 5);

    a1.showBalance();

    a1.deposit(2000);
    a1.showBalance();

    a1.withdraw(3000);

    a1.showBalance();

    a1.computeInterest();

    return 0;
}
Explanation of the Program
initialize()
This function initializes account balance and interest rate.
deposit()
Adds money to the account balance.
withdraw()
Subtracts money if sufficient balance exists.


showBalance()
Displays the current account balance.
computeInterest()
Calculates interest using the formula:
Example Calculation
If:
Balance = 10000
Rate = 5%
Then:
So, the interest will be ₹500.
Advantages of Using Classes in B Systems
Data protection
Easy maintenance
Organized code
Real-world representation
Better security
Importance of Object-Oriented Programming in C++
Object-Oriented Programming is highly important in modern software development. It allows developers to build large applications efficiently.
Benefits of OOP:
Reusability
Modularity
Security
Easy debugging
Better maintenance
Applications of OOP include:
Hospital management systems
School management systems
E-commerce applications
Mobile applications


Conclusion
C++ is a powerful programming language that supports object-oriented programming concepts. In this article, we studied three important programs:
Swapping two variables using Call by Reference
Constructor Overloading
Account Class Implementation
The first program explained how references allow direct modification of variables. The second program demonstrated constructor overloading, which provides multiple ways to initialize objects. The third program implemented a banking account system using classes and member functions.

These programs help students understand the practical implementation of OOP concepts in C++. They are essential for  students and beginner programmers because they provide a strong foundation for advanced programming and software development.

By learning these concepts carefully, students can improve their programming skills and develop efficient real-world applications in C++.

Comments

All Time

Why Cockroach Janata Party Is Trending Across India

Cockroach Janata Party: Meme, Movement, or the Voice of India’s Youth? Introduction In today’s digital world, trends are born overnight. A single meme, a viral hashtag, or a funny name can suddenly dominate social media platforms across India. One such trend that has recently captured the attention of millions is Cockroach Janata Party. At first glance, the name sounds humorous, unusual, and even strange. Many people see it as just another internet joke. However, if we look deeper, we can understand that this trend reflects something much larger than comedy. It represents frustration, sarcasm, creativity, and the emotions of a generation that wants to be heard. India has one of the world’s youngest populations. Millions of young people are searching for jobs, building online careers, learning new skills, creating content, and trying to survive in a highly competitive environment. In such a situation, internet culture becomes more than entertainment—i...

Focus, Discipline & Execution: What Humans Can Learn from Powerful Animals

Focus, Discipline & Execution: What Humans Can Learn from Powerful Animals Description In the wild, animals survive through instinct, patience, focus, and fearless execution. From the sharp vision of the eagle to the fearless mindset of the lion and the strategic patience of the wolf, nature teaches powerful life lessons that humans can apply in daily life.  This motivational article explores how animal behavior reflects success principles like leadership, discipline, vision, teamwork, confidence, and execution. If humans followed these natural instincts with purpose and consistency, success would become unstoppable. Focus, Discipline & Execution: The Animal Mindset Every Human Needs Nature is the greatest teacher in the world. Long before books, schools, and motivational speakers existed, animals were already surviving, leading, hunting, protecting families, and adapting to difficult situations. Every animal carries a uniq...

Urgent Request to Investigate and Remove Suspicious 7-Day Loan Applications from Indian Platforms

Urgent Request to Investigate and Remove Suspicious 7-Day Loan Applications from Indian Platforms India is rapidly growing in the field of digital technology and online financial services. Millions of people now depend on mobile applications for emergency loans and financial support. However, along with genuine financial platforms, several suspicious instant loan applications are allegedly causing serious harm to users through privacy violations, digital harassment, and mental pressure. Many of these applications are promoted aggressively through Google Play Store advertisements, Facebook Ads, Instagram promotions, and other social media platforms. These apps often provide small “7-day loans” and target financially vulnerable users who need urgent money. The major concern begins when users install these applications. During installation, the apps request dangerous permissions such as: - Contact List Access - Gallery Access - SMS Permission - Call Log...

Searching The Internet Without Screens — The Future Is Coming

Searching The Internet Without Screens — The Future Is Coming” Introduction For decades, screens have controlled the digital world. From bulky desktop monitors to smartphones that rarely leave our hands, screens became the center of human communication, learning, entertainment, and business. Every search, every message, every video, and almost every online experience depends on looking at a screen. But technology is changing faster than ever before. A new future is quietly approaching — a future where humans may search the internet without touching or even looking at traditional screens. Instead of phones and laptops, people may interact with the internet using voice, eyes, gestures, smart glasses, artificial intelligence, brain signals, and holographic systems. This idea once sounded like science fiction. Today, it is becoming reality. Major technology companies are investing billions of dollars into wearable devices, AI assistants, augm...

How to Start a Clothing Brand from Home Complete Beginner Guide

How to Start a Clothing Brand from Home  Complete A to Z Guide for Beginners Starting a clothing brand from home is no longer just a dream. thousands of creators, students, YouTubers, and small business owners are building successful fashion brands directly from their bedrooms using print-on-demand, social media marketing, AI tools, and eCommerce websites. Hii You do not need a factory, a huge office, or millions of rupees to start. What you really need is a smart idea, consistency, branding knowledge, and the courage to begin. Today, many successful online clothing brands started with just one T-shirt design and a smartphone. Some creators are earning through Instagram Reels, YouTube Shorts, Facebook monetization, and online stores simultaneously. This article will teach you everything step-by-step — from choosing a brand name to creating designs, building a website, advertising your products, connecting your shop links with YouTube and Faceboo...

Human Psychology and the Human Brain:Understanding How We Think, Decide, and Shape Our Reality

Human Psychology and the Human Brain: Understanding How We Think, Decide, and Shape Our Reality Human psychology and the human brain together form the foundation of everything we think, feel, decide, and create. From simple daily habits to complex life-changing decisions, our brain silently controls our behavior. Understanding this system is not only useful for doctors or scientists, but also for entrepreneurs, creators, leaders, students, and anyone who wants to grow consciously in life. This article explores human psychology, brain functioning, decision-making patterns, authority behavior, fear responses, and how awareness changes outcomes, based on modern psychology and neuroscience. 1. What Is Human Psychology? Human psychology is the scientific study of: Thoughts Emotions Behavior Motivation Social interaction It explains why people behave the way they do, not just what they do. Psychology answers questions like: Why do people reac...

Top Mountain Destinations in India for Travel and Photography

Hidden Natural Places: Mountain Travel Guide & Nature Photography Tips India is one of the most beautiful countries in the world when it comes to nature, mountains, forests, waterfalls, rivers, deserts, and hidden travel destinations.  While millions of tourists visit famous places like Goa, Manali, Shimla, and Kashmir every year, there are still many hidden natural places in India that remain unexplored by the majority of travelers. For travel lovers, vloggers, photographers, bloggers, and adventure seekers, these hidden places offer peace, beauty, and unforgettable experiences. If you love exploring mountains, capturing nature photography, or creating travel content for YouTube and social media, then these destinations can become perfect travel spots for your next adventure. In this article, we will explore some of India’s hidden natural places, mountain travel tips, and professional nature photography tips that can help you create amazing memories a...

Future AI ! 2030 Me Smartphones Kaise Honge? Yeh Sunke Hosh Ud Jayenge!

🔥 Introduction: AI Ka Jadoo Aur Smartphones Ka Future Aaj ka zamaana Artificial Intelligence (AI) ka hai. Har cheez me AI ka use ho raha hai – chahe woh smart assistants ho, self-driving cars ho ya automated content creation. Lekin 2030 tak smartphones kaise honge? Kya humare haath me physical devices rahenge ya AI sab kuch virtual bana dega? Yeh article aapko ek shocking future vision dene wala hai jo aapko hairaan kar dega! 😱🚀 🔮 2030 Me Smartphones Kaise Honge? 2030 me smartphones ekdum futuristic honge. Aaj jo hum touchscreens aur apps use kar rahe hain, shayad woh sab obsolete (purane) ho jayenge . AI-based smartphones aise honge jo bina kisi physical screen ke kaam karenge aur aapke mind se direct control honge! 1️⃣ Full AI-Driven Smartphones (No Apps, Just AI!)   ✅ Apps ka zamana khatam ho jayega! Har smartphone ek AI-powered assistant ban jayega jo aapki har zaroorat ko samjhega aur turant solutions dega. ✅ Aap sirf voice ya thought commands se apna phone c...

How to Earn Online Using PayPal and Payoneer | Complete Setup and International Payment Guide

Introduction Today, a large number of people are earning money online by offering services, creating digital content, promoting affiliate products, or freelancing. However, receiving payments from international clients is challenging without a reliable global payment gateway. PayPal and Payoneer are two trusted platforms used by freelancers, bloggers, YouTubers, agencies, and online businesses across the world to receive international payments securely. This guide explains how to create and verify accounts, link bank accounts, receive payments from different online platforms, withdraw earnings, fees, transfer time, and how to earn money online using PayPal and Payoneer. --- Difference Between PayPal and Payoneer Feature PayPal Payoneer Purpose Global online payments & checkout Freelancing and business international payments Verification Simple Slightly more detailed Fees Higher fees Lower and stable fees Supported Countries 200+ 150+ Bank Withdrawal Direct to bank Virtual global ba...