0% found this document useful (0 votes)
20 views17 pages

C++ Object-Oriented Programming Examples

The document outlines various C++ programming exercises focusing on object-oriented concepts such as classes, constructors, destructors, function overloading, and dynamic memory allocation. It includes detailed algorithms, code snippets, and expected outputs for each exercise, demonstrating practical applications of these concepts. Key topics include class design, encapsulation, friend functions, static members, and memory management.

Uploaded by

yasyash4966
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views17 pages

C++ Object-Oriented Programming Examples

The document outlines various C++ programming exercises focusing on object-oriented concepts such as classes, constructors, destructors, function overloading, and dynamic memory allocation. It includes detailed algorithms, code snippets, and expected outputs for each exercise, demonstrating practical applications of these concepts. Key topics include class design, encapsulation, friend functions, static members, and memory management.

Uploaded by

yasyash4966
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Rajarajeswari College of Engineering

(An Autonomous Institute, Affiliated Visvesvaraya Technological University, Belagavi ,


Approved by AICTE, UGC & GoK, Accredited by ISO 9001-2015 Certified Institution)
Sponsored by: MOOGAMBIGAI CHARITABLE AND EDUCATIONAL TRUST
Department of Computer Science and Engineering
Class :II year/III SEM/ D sec Name : [Link],AP/CSE

PROGRAMS – MODULE-I and II (2025-26)


OBJECT ORIENTED PROGRAMMING WITH C++-B24IC362

[Link] a C++ program for a class named Student with private members: name (string),
rollNumber (int), and totalMarks (double). Implement a Parameterized Constructor to ini alize
these [Link]fine a member func on displayDetails() outside the class using the Scope Resolu on
Operator to print the student's informa on

Algorithm:

Private members:

name, rollNumber, and totalMarks are encapsulated inside the class.

Parameterized constructor:

Ini alizes the private members when an object is created.

Scope Resolu on Operator (::):

Used to define displayDetails() outside the class body.

Object Crea on:

Student s1("XYZ", 101, 89.5); calls the parameterized constructor.

Program:

#include <iostream>

#include <string>

using namespace std;

// Class Declara on

class Student {

private:

string name;

int rollNumber;

double totalMarks;

public:

// Parameterized Constructor
Student(string n, int r, double m) {

name = n;

rollNumber = r;

totalMarks = m;

// Func on Declara on

void displayDetails();

};

// Member Func on Defini on using Scope Resolu on Operator

void Student::displayDetails() {

cout << "---- Student Details ----" << endl;

cout << "Name: " << name << endl;

cout << "Roll Number: " << rollNumber << endl;

cout << "Total Marks: " << totalMarks << endl;

// Main Func on

int main() {

// Create object using Parameterized Constructor

Student s1("John Doe", 101, 89.5);

// Display Student Details

[Link]();

return 0;

OUTPUT:

---- Student Details ----

Name: XYZ

Roll Number: 101

Total Marks: 89.5


[Link] a class named Distance with a private member meters (double). Implement a member
func on to set the distance. Write a Friend Func on called addDistance() that takes two Distance
objects as arguments (Passing Objects to func ons) and returns their sum (as a double value
represen ng the total distance in meters).

Algorithm:

1. Private Member:
meters holds the distance value; it’s private and can’t be accessed directly outside the
class.
2. Member Func on:
setDistance(double m) assigns a value to meters.
3. Friend Func on:
addDistance(Distance d1, Distance d2) is a non-member func on that can access
private members because it’s declared as a friend inside the class.
4. Passing Objects to Func on:
The func on takes two Distance objects by value, accesses their private members, and
returns the sum.

#include <iostream>

using namespace std;

class Distance {

private:

double meters; // Private data member

public:

// Member func on to set distance

void setDistance(double m) {

meters = m;

// Friend func on declara on

friend double addDistance(Distance d1, Distance d2);

};

// Friend func on defini on

double addDistance(Distance d1, Distance d2) {

// Accessing private members directly since it's a friend

return [Link] + [Link];

int main() {
Distance d1, d2;

// Se ng distances

[Link](12.5);

[Link](7.8);

// Calling friend func on to add distances

double total = addDistance(d1, d2);

cout << "Distance 1: 12.5 meters" << endl;

cout << "Distance 2: 7.8 meters" << endl;

cout << "Total Distance: " << total << " meters" << endl;

return 0;

OUTPUT:

Distance 1: 12.5 meters

Distance 2: 7.8 meters

Total Distance: 20.3 meters

[Link] a class Project to manage project IDs. Include a Sta c Class Member projectCount to keep

track of the total number of Project objects created. Implement an Inline Func on showCount() to

display this count. Demonstrate the effect of Object Assignment by crea ng one object and assigning

it to another.

A sta c class member projectCount to track the number of Project objects.

A constructor to increment projectCount.

An inline func on showCount() to display the total count.

Demonstrate object assignment and how it affects the sta c counter.

Explana on:

1. sta c int projectCount; keeps a global count across all objects.

2. Constructor increments projectCount every me a new object is created.

3. showCount() is inline to display the count quickly.

4. Object assignment (Project p2 = p1;) does not create a new object in the sense of constructor
call (copy constructor is called, but sta c counter is not incremented if default copy constructor
is used).

5. Both p1 and p2 share the same projectCount because it’s sta c.

#include <iostream>
using namespace std;

class Project {

private:

int projectID; // Unique ID for each project

public:

sta c int projectCount; // Sta c member to track total projects

// Constructor

Project(int id) : projectID(id) {

projectCount++; // Increment count whenever a new object is created

cout << "Project " << projectID << " created." << endl;

// Inline func on to show count

inline void showCount() {

cout << "Total Projects: " << projectCount << endl;

// Func on to display project ID

void display() {

cout << "Project ID: " << projectID << endl;

};

// Ini alize sta c member

int Project::projectCount = 0;

int main() {

// Crea ng first project

Project p1(101);

[Link]();

// Object assignment
Project p2 = p1; // Copy assignment

[Link]();

// Display project IDs

cout << "p1: ";

[Link]();

cout << "p2: ";

[Link]();

return 0;

[Link] a C++ program for a class TempData. Include a constructor and a destructor, and print

a message inside each to illustrate When Constructors and Destructors are Executed.

Implement a member func on createDefault() that Returns an Object of type TempData

ini alized with default values.

Algorithm

Constructor prints a message whenever an object is created.

Destructor prints a message when an object goes out of scope (i.e., destroyed).

createDefault() is a sta c member func on that:

Creates a TempData object locally.

Returns it by value.

Demonstrates the temporary object destruc on sequence.

This helps visualize object lifecycle — crea on, return, and destruc on.

Program:

#include <iostream>

using namespace std;

class TempData {

private:

int temperature;

string loca on;


public:

// Constructor

TempData(int t, string loc) {

temperature = t;

loca on = loc;

cout << "Constructor executed: Object created for " << loca on << " with temperature "
<< temperature << "°C" << endl;

// Destructor

~TempData() {

cout << "Destructor executed: Object for " << loca on << " is being destroyed." << endl;

// Member func on to display data

void display() {

cout << "Loca on: " << loca on << ", Temperature: " << temperature << "°C" << endl;

// Sta c member func on to return a default object

sta c TempData createDefault() {

cout << "Crea ng default TempData object..." << endl;

TempData defaultObj(25, "Default City");

return defaultObj;

};

// Main func on

int main() {

cout << "Inside main()" << endl;

// Crea ng object using parameterized constructor

TempData obj1(30, "Bangalore");

[Link]();
cout << "\nCalling createDefault()..." << endl;

TempData obj2 = TempData::createDefault();

[Link]();

cout << "\nEnd of main()" << endl;

return 0;

Sample Output:

Inside main()

Constructor executed: Object created for Bangalore with temperature 30°C

Loca on: Bangalore, Temperature: 30°C

Calling createDefault()...

Crea ng default TempData object...

Constructor executed: Object created for Default City with temperature 25°C

Destructor executed: Object for Default City is being destroyed.

Loca on: Default City, Temperature: 25°C

End of main()

Destructor executed: Object for Default City is being destroyed.

Destructor executed: Object for Bangalore is being destroyed.

[Link] a class Inventory with private members itemName and itemPrice. Write a program
to use the new operator to dynamically allocate an Array of 3 Inventory Objects. Use a
Pointer to Objects to input data for all three items and then display the details of the item
with the lowest price. Use the delete operator to free the allocated memory.

Program Explana on

1. Inventory class has two private members:

itemName

itemPrice

2. Member func ons:

getData() → inputs item details


displayData() → displays details

getPrice() → returns price for comparison

3. In main():

Dynamically allocate an array of 3 objects:

Inventory* items = new Inventory[3];

Use pointer arithme c (items + i) to input and access objects.

Determine the item with the lowest price using comparison.

Display that item.

Finally, deallocate memory with:

delete[] items;

Program

#include <iostream>

#include <string>

using namespace std;

class Inventory {

private:

string itemName;

float itemPrice;

public:

// Func on to input data

void getData() {

cout << "Enter Item Name: ";

cin >> itemName;

cout << "Enter Item Price: ";

cin >> itemPrice;

// Func on to display data

void displayData() const {

cout << "Item Name: " << itemName << ", Price: " << itemPrice << endl;

}
// Func on to get price (for comparison)

float getPrice() const {

return itemPrice;

};

int main() {

int n = 3;

// Dynamically allocate memory for an array of 3 Inventory objects

Inventory* items = new Inventory[n];

cout << "Enter details of " << n << " items:\n";

// Input data using pointer to objects

for (int i = 0; i < n; ++i) {

cout << "\nItem " << i + 1 << ":\n";

(items + i)->getData();

// Find the item with the lowest price

int minIndex = 0;

for (int i = 1; i < n; ++i) {

if ((items + i)->getPrice() < (items + minIndex)->getPrice()) {

minIndex = i;

cout << "\nItem with the lowest price:\n";

(items + minIndex)->displayData();

// Free the dynamically allocated memory

delete[] items;
cout << "\nMemory released successfully using delete[]." << endl;

return 0;

Output:

Enter details of 3 items:

Item 1:

Enter Item Name: Pen

Enter Item Price: 10

Item 2:

Enter Item Name: Notebook

Enter Item Price: 25

Item 3:

Enter Item Name: Pencil

Enter Item Price: 5

Item with the lowest price:

Item Name: Pencil, Price: 5

Memory released successfully using delete[].

[Link] a func on display. Overload this func on to handle and display the following: 1. An
integer value. 2. A character string. 3. Two integer values, using the second integer as a Default
Func on Argument (e.g., set the default value to 10). Demonstrate all three overloaded versions.

Algorithm:

Func on Overloading means using the same func on name with different parameter lists.

Here, three versions of display() are defined:

display(int) → prints a single integer.

display(string) → prints a string.

display(int, int = 10) → prints two integers; the second has a default value (10) if not
provided.
The compiler automa cally selects the correct func on version based on the arguments passed.

Program:

#include <iostream>

#include <string>

using namespace std;

// Func on to display an integer value

void display(int num) {

cout << "Displaying Integer Value: " << num << endl;

// Func on to display a string

void display(string text) {

cout << "Displaying String: " << text << endl;

// Func on to display two integers (second one has a default value)

void display(int num1, int num2 = 10) {

cout << "Displaying Two Integers: " << num1 << " and " << num2 << endl;

int main() {

cout << "Demonstra on of Func on Overloading with Default Argument\n\n";

// Calls version 1: integer

display(25);

// Calls version 2: string

display("Hello, C++");

// Calls version 3: two integers (with both arguments)

display(5, 15);

// Calls version 3: only one argument (uses default value for second)
display(7);

return 0;

Output:

Demonstra on of Func on Overloading with Default Argument

Displaying Integer Value: 25

Displaying String: Hello, C++

Displaying Two Integers: 5 and 15

Displaying Two Integers: 7 and 10

[Link] a class StringWrapper that holds a dynamically allocated character array (string).
Implement a Copy Constructor to perform a deep copy of the string data. Write a func on
printString that accepts a Reference to a StringWrapper object. Demonstrate how the copy
constructor is invoked when a StringWrapper object is passed by value to a func on.

Algorithm

StringWrapper class

Uses a dynamically allocated character array (char* str).

The constructor allocates memory and copies the string.

The copy constructor performs a deep copy — it allocates new memory and copies the string
from another object, ensuring the two objects don’t share the same memory.

The destructor frees memory to prevent leaks.

printString() → accepts object by reference, so no copy constructor is invoked.

showCopy() → accepts object by value, so copy constructor is automa cally invoked to create a
local copy.

Program

#include <iostream>

#include <cstring>

using namespace std;

class StringWrapper {

private:

char* str; // Pointer to dynamically allocated character array

public:

// Constructor
StringWrapper(const char* s = "") {

cout << "Constructor called." << endl;

str = new char[strlen(s) + 1]; // Allocate memory

strcpy(str, s); // Copy string content

// Copy Constructor (performs deep copy)

StringWrapper(const StringWrapper& obj) {

cout << "Copy Constructor called." << endl;

str = new char[strlen([Link]) + 1]; // Allocate separate memory

strcpy(str, [Link]); // Copy content

// Destructor

~StringWrapper() {

cout << "Destructor called for string: " << str << endl;

delete[] str; // Free allocated memory

// Func on to print the string

void print() const {

cout << "String: " << str << endl;

};

// Func on that accepts a reference to StringWrapper

void printString(const StringWrapper& s) {

cout << "Inside printString (pass by reference): ";

[Link]();

// Func on that accepts a StringWrapper by value

void showCopy(StringWrapper s) {

cout << "Inside showCopy (pass by value): ";


[Link]();

int main() {

cout << "Crea ng object s1..." << endl;

StringWrapper s1("Hello, World!");

cout << "\nPassing s1 by reference to printString()..." << endl;

printString(s1); // No copy constructor call (reference passed)

cout << "\nPassing s1 by value to showCopy()..." << endl;

showCopy(s1); // Copy constructor called here

cout << "\nBack in main()." << endl;

return 0;

Output:

Crea ng object s1...

Constructor called.

Passing s1 by reference to printString()...

Inside printString (pass by reference): String: Hello, World!

Passing s1 by value to showCopy()...

Copy Constructor called.

Inside showCopy (pass by value): String: Hello, World!

Destructor called for string: Hello, World!

Back in main().

Destructor called for string: Hello, World!

[Link] a class Calculator with a public func on add(int a, int b) and a public integer member
lastResult. Write a C++ program to demonstrate: 1. Using a Pointer to a Class Member to access and

modify the lastResult member. 2. Using a pointer to a class member func on to call the add()
func on.

Algorithm:

int Calculator::*ptrData → Pointer to integer data member of Calculator.


int (Calculator::*ptrFunc)(int, int) → Pointer to member func on taking two int arguments and
returning int.

Access and call syntax:

 object.*ptrData → Access data member via pointer.

 (object.*ptrFunc)(args) → Call member func on via pointer.

Program:

#include <iostream>

using namespace std;

class Calculator {

public:

int lastResult; // Public data member

// Member func on to add two integers

int add(int a, int b) {

lastResult = a + b;

return lastResult;

};

int main() {

Calculator calc; // Create an object

// Pointer to data member (int Calculator::*)

int Calculator::*ptrData = &Calculator::lastResult;

// Pointer to member func on (int (Calculator::*)(int, int))

int (Calculator::*ptrFunc)(int, int) = &Calculator::add;

// --- Accessing and modifying data member through pointer ---

cout << "Accessing Data Member via Pointer:\n";

calc.*ptrData = 0; // Ini alize lastResult via pointer

cout << "Ini al lastResult = " << calc.*ptrData << endl;


// --- Calling member func on through func on pointer ---

cout << "\nCalling Member Func on via Pointer:\n";

int result = (calc.*ptrFunc)(10, 20); // Equivalent to [Link](10, 20)

cout << "Addi on Result = " << result << endl;

// --- Displaying updated lastResult using pointer ---

cout << "Updated lastResult (via pointer) = " << calc.*ptrData << endl;

// --- Modifying lastResult through pointer ---

calc.*ptrData = 100;

cout << "\nModified lastResult = " << calc.*ptrData << endl;

return 0;

Output:

Accessing Data Member via Pointer:

Ini al lastResult = 0

Calling Member Func on via Pointer:

Addi on Result = 30

Updated lastResult (via pointer) = 30

Modified lastResult = 100

You might also like