Trending

Object Oriented Programming Lab Questions C++

Lab Question: Class and Object Basics

In this Object-Oriented Programming we focus on the topic related to C++ Object-Oriented Programming lab questions.

Question:
Create a C++ class called “Book” with the following attributes:

  • title (string)
  • author (string)
  • publicationYear (int)
  • isbn (string)

Implement a constructor to initialize these attributes when an object of the class is created.

Object Oriented Programming Lab Questions C++
Object Oriented Programming Lab Questions C++

Next, instantiate two objects of the “Book” class, one representing a book titled “The Catcher in the Rye” by “J.D. Salinger,” published in “1951” with ISBN “978-0-316-76948-0,” and the other representing a book titled “To Kill a Mockingbird” by “Harper Lee,” published in “1960” with ISBN “978-0-06-112008-4.”

Finally, display the details of both books, including their titles, authors, publication years, and ISBNs.

Explanation:

This lab question focuses on the basics of creating a class, defining attributes, implementing a constructor, and creating objects of that class. It also demonstrates how to access and display the object’s attributes.

Sample C++ Code:

#include <iostream>#include <string>using namespace std;class Book {public:    // Constructor to initialize attributes    Book(string t, string a, int year, string i) {        title = t;        author = a;        publicationYear = year;        isbn = i;    }    // Function to display book details    void displayDetails() {        cout << "Title: " << title << endl;        cout << "Author: " << author << endl;        cout << "Publication Year: " << publicationYear << endl;        cout << "ISBN: " << isbn << endl;    }private:    string title;    string author;    int publicationYear;    string isbn;};int main() {    // Create two Book objects    Book book1("The Catcher in the Rye", "J.D. Salinger", 1951, "978-0-316-76948-0");    Book book2("To Kill a Mockingbird", "Harper Lee", 1960, "978-0-06-112008-4");    // Display book details    cout << "Book 1 Details:" << endl;    book1.displayDetails();    cout << "\nBook 2 Details:" << endl;    book2.displayDetails();    return 0;}

In this example, we create a “Book” class with attributes and a constructor to initialize those attributes. Then, we instantiate two “Book” objects with different book details and use the display Details method to print their information.

Object Oriented Programming

Object-Oriented Programming (OOP) in C++ is a programming paradigm that uses objects, which are instances of classes, to design and implement software systems. OOP promotes the organization of code into reusable, self-contained units called classes, which encapsulate both data (attributes) and the operations (methods or functions) that can be performed on that data. C++ is a language well-suited for OOP due to its support for classes and objects.

Key features of Object-Oriented Programming in C++ include:

  1. Classes and Objects: Classes serve as blueprints for creating objects. An object is an instance of a class, and each object has its own set of attributes (data members) and can perform operations (member functions) defined in the class.
  2. Encapsulation: Encapsulation is the concept of bundling data and methods that operate on that data into a single unit (a class). It enforces access control to protect the integrity of the data, allowing only authorized methods to modify it.
  3. Abstraction: Abstraction involves simplifying complex systems by modeling them with a limited set of essential characteristics. Classes in OOP provide a level of abstraction by hiding implementation details and exposing only the necessary interfaces to interact with the object.
  4. Inheritance: Inheritance allows you to create new classes (derived or subclass) by inheriting the properties and behaviors of an existing class (base or superclass). This promotes code reuse and the creation of hierarchies of related classes.
  5. Polymorphism: Polymorphism enables objects of different classes to be treated as objects of a common base class. It allows for method overriding, where a derived class can provide its implementation of a method defined in the base class. This is achieved through virtual functions and dynamic binding.
  6. Modularity: OOP promotes modularity by breaking down a complex system into smaller, more manageable components (classes). Each class focuses on a specific aspect of the system, making it easier to design, develop, and maintain software.
  7. Message Passing: Objects communicate with each other by sending messages. In C++, this is primarily achieved through method calls on objects.
  8. Constructor and Destructor: C++ classes have constructors (special member functions) for initializing objects when they are created and destructors for cleaning up resources when objects are destroyed.

Table of Contents

Now, without further do let’s start to solve the programming problems.

Write a programs to demonstrate the insertion and extraction operators

Here is the programe…

#include<iostream>

using namespace std;

int main() {
int num;
string name;

// Demonstrate the extraction (>>) operator to input data
cout << “Enter an integer: “;
cin >> num;

cout << “Enter your name: “;
cin.ignore(); // Clear the newline character left in the buffer
getline(cin, name);

// Demonstrate the insertion (<<) operator to output data
cout << “You entered: ” << num << endl;
cout << “Hello, ” << name << “! Welcome to C++ programming.” << endl;

return 0;

}

Write a program to demonstrate the insertion and extraction manipulators.

#include<iostream>

#include<iomanip> // Include the header for manipulators

using namespace std;

int main() {
int num = 12345;
double pi = 3.14159265359;

// Demonstrate the insertion manipulator to format output
cout << “Formatted Output:” << endl;
cout << “Integer: ” << setw(10) << num << endl; // Set field width
cout << “Pi: ” << setprecision(5) << fixed << pi << endl; // Set precision and fixed-point notation
cout << “Hexadecimal: ” << hex << num << endl; // Display in hexadecimal

// Demonstrate the extraction manipulator to format input
int userInput;
cout << “\nEnter an integer in octal format (e.g., 077): “;
cin >> oct >> userInput; // Read octal input
cout << “You entered in decimal: ” << userInput << endl;

return 0;

}

Write a program to demonstrate the insertion and extraction dynamic memory management.

#include<iostream>

using namespace std;

int main() {
int size;

// Prompt the user to enter the size of the dynamic array
cout << “Enter the size of the dynamic array: “;
cin >> size;

// Dynamically allocate an integer array of the specified size
int* dynamicArray = new int[size];

// Insert values into the dynamic array
cout << “Enter ” << size << ” integers:” << endl;
for (int i = 0; i < size; ++i) {
cin >> dynamicArray[i];
}

// Display the values from the dynamic array
cout << “Values in the dynamic array:” << endl;
for (int i = 0; i < size; ++i) {
cout << dynamicArray[i] << ” “;
}
cout << endl;

// Deallocate the dynamically allocated memory
delete[] dynamicArray;

return 0;

}

Write a program to demonstrate default arguments

#include<iostream>

using namespace std;

// Function with default arguments
void printMessage(string message = “Hello, World!”) {
cout << message << endl;
}

int main() {
cout << “Calling printMessage() with the default argument:” << endl;
printMessage(); // Calls the function with the default message

cout << “\nCalling printMessage() with a custom message:” << endl;
printMessage(“Welcome to C++ Programming!”); // Calls the function with a custom message

return 0;

}

Write a program to demonstrate inline function

#include<iostream>

using namespace std;

// Inline function definition
inline int add(int a, int b) {
return a + b;
}

int main() {
int num1, num2, result;

cout << “Enter two numbers: “;
cin >> num1 >> num2;

// Call the inline function
result = add(num1, num2);

cout << “The sum of ” << num1 << ” and ” << num2 << ” is: ” << result << endl;

return 0;

}

Write a program to demonstrate function overloading

#include<iostream>

using namespace std;

// Function to add two integers
int add(int a, int b) {
return a + b;
}

// Function to add two doubles
double add(double a, double b) {
return a + b;
}

// Function to concatenate two strings
string add(string a, string b) {
return a + b;
}

int main() {
int num1 = 5, num2 = 7;
double dbl1 = 3.14, dbl2 = 2.71;
string str1 = “Hello, “, str2 = “World!”;

// Call the overloaded functions
int sumInt = add(num1, num2);
double sumDbl = add(dbl1, dbl2);
string concatStr = add(str1, str2);

cout << “Sum of integers: ” << sumInt << endl;
cout << “Sum of doubles: ” << sumDbl << endl;
cout << “Concatenated string: ” << concatStr << endl;

return 0;

}

Write a program to demonstrate class and object

#include<iostream>

using namespace std;

// Define a class called “Student”
class Student {
public:
// Public member variables
string name;
int age;

// Public member function to display student information
void displayInfo() {
cout << “Name: ” << name << endl;
cout << “Age: ” << age << endl;
}

};

int main() {
// Create two objects of the “Student” class
Student student1, student2;

// Set data for the first student
student1.name = “Alice”;
student1.age = 20;

// Set data for the second student
student2.name = “Bob”;
student2.age = 22;

// Call the displayInfo() method for each student object
cout << “Student 1 Information:” << endl;
student1.displayInfo();

cout << “\nStudent 2 Information:” << endl;
student2.displayInfo();

return 0;

}

Write a program to demonstrate array of object and pointer of objects

#include<iostream>

#include<string>

using namespace std;

// Define a class called “Student”
class Student {
public:
string name;
int age;

// Parameterized constructor
Student(string n, int a) {
name = n;
age = a;
}

// Member function to display student information
void displayInfo() {
cout << “Name: ” << name << endl;
cout << “Age: ” << age << endl;
}

};

int main() {
// Create an array of Student objects
Student students[3] = {
Student(“Alice”, 20),
Student(“Bob”, 22),
Student(“Charlie”, 21)
};

// Display information using the array of objects
cout << “Using an array of objects:” << endl;
for (int i = 0; i < 3; i++) {
cout << “\nStudent ” << i + 1 << ” Information:” << endl;
students[i].displayInfo();
}

// Create an array of pointers to Student objects
Student* studentPtrs[3];
studentPtrs[0] = new Student(“David”, 19);
studentPtrs[1] = new Student(“Eve”, 23);
studentPtrs[2] = new Student(“Frank”, 20);

// Display information using the array of pointers to objects
cout << “\nUsing an array of pointers to objects:” << endl;
for (int i = 0; i < 3; i++) {
cout << “\nStudent ” << i + 1 << ” Information:” << endl;
studentPtrs[i]->displayInfo();
}

// Deallocate memory for objects pointed to by pointers
for (int i = 0; i < 3; i++) {
delete studentPtrs[i];
}

return 0;

}

Write a program to demonstrate constructer and destructor

#include<iostream>

using namespace std;

// Define a class called “Student”
class Student {
public:
// Constructor
Student(string n, int a) {
name = n;
age = a;
cout << “Constructor called for ” << name << endl;
}

// Destructor
~Student() {
cout << “Destructor called for ” << name << endl;
}

// Member function to display student information
void displayInfo() {
cout << “Name: ” << name << endl;
cout << “Age: ” << age << endl;
}

private:
string name;
int age;
};

int main() {
// Create Student objects using the constructor
Student student1(“Alice”, 20);
Student student2(“Bob”, 22);

// Display information using the member function
cout << “Displaying information using member function:” << endl;
student1.displayInfo();
student2.displayInfo();

// Objects go out of scope and destructors are called automatically

return 0;

}

Write a program to demonstrate static members.

#include<iostream>

using namespace std;

// Define a class called “Counter” with a static member
class Counter {
public:
static int count; // Static member variable

// Constructor to increment the count
Counter() {
count++;
}

// Destructor to decrement the count
~Counter() {
count–;
}

};

// Initialize the static member variable
int Counter::count = 0;

int main() {
// Create three Counter objects
Counter obj1, obj2, obj3;

// Display the current count using the static member
cout << “Current count: ” << Counter::count << endl;

// Create two more Counter objects
Counter obj4, obj5;

// Display the updated count
cout << “Updated count: ” << Counter::count << endl;

return 0;

}

Write a program to demonstrate this pointer

#include<iostream>

using namespace std;

class MyClass {
private:
int value;

public:
// Constructor to initialize the value
MyClass(int v) {
this->value = v;
}

// Member function to display the value using this pointer
void displayValue() {
cout << “Value: ” << this->value << endl;
}

// Member function to compare values
bool isEqual(MyClass other) {
return this->value == other.value;
}

};

int main() {
// Create two instances of MyClass
MyClass obj1(42);
MyClass obj2(23);

// Display values using the displayValue method
obj1.displayValue();
obj2.displayValue();

// Compare values using isEqual method
if (obj1.isEqual(obj2)) {
cout << “Values are equal.” << endl;
} else {
cout << “Values are not equal.” << endl;
}

return 0;

}

Write a program to demonstrate friend function

#include<iostream>

using namespace std;

class MyClass; // Forward declaration

// Friend function declaration
void displayValue(const MyClass& obj);

class MyClass {
private:
int value;

public:
MyClass(int v) : value(v) {}

// Declare the friend function
friend void displayValue(const MyClass& obj);

};

// Friend function definition
void displayValue(const MyClass& obj) {
cout << “Value: ” << obj.value << endl;
}

int main() {
MyClass obj(42);

// Call the friend function to display the private member
displayValue(obj);

return 0;

}

People also read:- Is c++ is better than c programming?

Write a program to demonstrate friend class

#include<iostream>

using namespace std;

// Forward declaration of the FriendClass
class FriendClass;

// MyClass definition
class MyClass {
private:
int privateData;

public:
MyClass(int data) : privateData(data) {}

// FriendClass is declared as a friend
friend class FriendClass;

};

// FriendClass definition
class FriendClass {
public:
void accessPrivateData(const MyClass& obj) {
// FriendClass can access the private member of MyClass
cout << “FriendClass accessing privateData: ” << obj.privateData << endl;
}
};

int main() {
MyClass obj(42);
FriendClass friendObj;

// FriendClass accesses the private member of MyClass
friendObj.accessPrivateData(obj);

return 0;

}

Write a program to demonstrate unary operator overloading

#include<iostream>

using namespace std;

class MyNumber {
private:
int value;

public:
MyNumber(int val) : value(val) {}

// Overload the prefix increment operator (++)
MyNumber operator++() {
return MyNumber(++value);
}

// Overload the postfix increment operator (++)
MyNumber operator++(int) {
MyNumber temp(value);
value++;
return temp;
}

// Overload the prefix decrement operator (–)
MyNumber operator–() {
return MyNumber(–value);
}

// Overload the postfix decrement operator (–)
MyNumber operator–(int) {
MyNumber temp(value);
value–;
return temp;
}

// Display the current value
void display() {
cout << “Value: ” << value << endl;
}

};

int main() {
MyNumber num(5);

cout << “Original Value:” << endl;
num.display();

// Increment using prefix operator
MyNumber incremented1 = ++num;
cout << “Value after prefix increment:” << endl;
incremented1.display();

// Increment using postfix operator
MyNumber incremented2 = num++;
cout << “Value after postfix increment:” << endl;
incremented2.display();

// Decrement using prefix operator
MyNumber decremented1 = –num;
cout << “Value after prefix decrement:” << endl;
decremented1.display();

// Decrement using postfix operator
MyNumber decremented2 = num–;
cout << “Value after postfix decrement:” << endl;
decremented2.display();

return 0;

}

Write a program to demonstrate binary operator overloading

#include<iostream>

using namespace std;

class MyNumber {
private:
int value;

public:
MyNumber(int val) : value(val) {}

// Overload the binary addition operator (+)
MyNumber operator+(const MyNumber& other) {
return MyNumber(this->value + other.value);
}

// Display the current value
void display() {
cout << “Value: ” << value << endl;
}

};

int main() {
MyNumber num1(5);
MyNumber num2(3);

cout << “Value of num1:” << endl;
num1.display();

cout << “Value of num2:” << endl;
num2.display();

MyNumber result = num1 + num2;

cout << “Result of num1 + num2:” << endl;
result.display();

return 0;

}

Write a program to demonstrate type conversion

#include<iostream>

using namespace std;

class Distance {
private:
float feet;
float inches;

public:
Distance() : feet(0), inches(0) {}

// Constructor to initialize Distance object
Distance(float f, float i) : feet(f), inches(i) {}

// Display the Distance object
void display() {
cout << “Feet: ” << feet << ” Inches: ” << inches << endl;
}

// Conversion operator: Convert Distance to float (total inches)
operator float() {
return feet * 12 + inches;
}

};

int main() {
Distance dist(5, 6);

// Display the Distance object
cout << “Distance object:” << endl;
dist.display();

// Implicit type conversion from Distance to float
float totalInches = dist;
cout << “Total inches (implicit conversion): ” << totalInches << endl;

// Explicit type conversion from Distance to float
float anotherTotalInches = static_cast<float>(dist);
cout << “Total inches (explicit conversion): ” << anotherTotalInches << endl;

return 0;

}

Write a program to demonstrate access specifiers and different types of inheritances.

#include<iostream>

using namespace std;

// Base class with access specifiers
class Base {
public:
int publicVar;
Base() : publicVar(0), protectedVar(0), privateVar(0) {}

void publicMethod() {
cout << “Base class publicMethod() called” << endl;
}

protected:
int protectedVar;

void protectedMethod() {
cout << “Base class protectedMethod() called” << endl;
}

private:
int privateVar;

void privateMethod() {
cout << “Base class privateMethod() called” << endl;
}

};

// Public inheritance
class PublicDerived : public Base {
public:
void accessBaseMembers() {
cout << “PublicDerived accessing base class members:” << endl;
publicVar = 1;
protectedVar = 2;
// privateVar is not accessible here
publicMethod();
protectedMethod();
// privateMethod() is not accessible here
}
};

// Protected inheritance
class ProtectedDerived : protected Base {
public:
void accessBaseMembers() {
cout << “ProtectedDerived accessing base class members:” << endl;
publicVar = 1;
protectedVar = 2;
// privateVar is not accessible here
publicMethod();
protectedMethod();
// privateMethod() is not accessible here
}
};

// Private inheritance
class PrivateDerived : private Base {
public:
void accessBaseMembers() {
cout << “PrivateDerived accessing base class members:” << endl;
publicVar = 1;
protectedVar = 2;
// privateVar is not accessible here
publicMethod();
protectedMethod();
// privateMethod() is not accessible here
}
};

int main() {
// Public inheritance example
PublicDerived publicDerived;
publicDerived.accessBaseMembers();

// Protected inheritance example
ProtectedDerived protectedDerived;
// protectedDerived.accessBaseMembers(); // This line will result in a compilation error because accessBaseMembers is protected in ProtectedDerived

// Private inheritance example
PrivateDerived privateDerived;
// privateDerived.accessBaseMembers(); // This line will result in a compilation error because accessBaseMembers is private in PrivateDerived

return 0;

}

Write a programs to demonstrate constructor and destructors in inheritances

#include<iostream>

using namespace std;

class Base {
public:
Base() {
cout << “Base class constructor called” << endl;
}

~Base() {
cout << “Base class destructor called” << endl;
}

};

class Derived : public Base {
public:
Derived() {
cout << “Derived class constructor called” << endl;
}

~Derived() {
cout << “Derived class destructor called” << endl;
}

};

int main() {
cout << “Creating a Base object:” << endl;
Base baseObj;

cout << “\nCreating a Derived object:” << endl;
Derived derivedObj;

return 0;

}

Write a programs to demonstrate public and private derivation

#include<iostream>

using namespace std;

// Base class
class Base {
public:
void publicFunction() {
cout << “Base class publicFunction()” << endl;
}

void commonFunction() {
cout << “Base class commonFunction()” << endl;
}

private:
void privateFunction() {
cout << “Base class privateFunction()” << endl;
}
};

// Publicly derived class
class PublicDerived : public Base {
public:
void publicDerivedFunction() {
cout << “PublicDerived class publicDerivedFunction()” << endl;
}
};

// Privately derived class
class PrivateDerived : private Base {
public:
void privateDerivedFunction() {
cout << “PrivateDerived class privateDerivedFunction()” << endl;
}

// Access the commonFunction of Base class
void accessCommonFunction() {
commonFunction(); // Allowed, even though it’s private in Base
}

};

int main() {
// Public inheritance example
PublicDerived publicDerivedObj;
cout << “Using Public Inheritance:” << endl;
publicDerivedObj.publicFunction(); // Accessible
publicDerivedObj.publicDerivedFunction(); // Accessible
publicDerivedObj.commonFunction(); // Accessible
// publicDerivedObj.privateFunction(); // Not accessible (private in Base)

// Private inheritance example
PrivateDerived privateDerivedObj;
cout << “\nUsing Private Inheritance:” << endl;
// privateDerivedObj.publicFunction(); // Not accessible (inherited as private)
// privateDerivedObj.commonFunction(); // Not accessible (inherited as private)
// privateDerivedObj.privateFunction(); // Not accessible (private in Base)
privateDerivedObj.privateDerivedFunction(); // Accessible
privateDerivedObj.accessCommonFunction(); // Accessible (via a public member function)

return 0;

}

Write a programs to demonstrate ambiguities and inheritance and their solution

#include<iostream>

using namespace std;

// Base class A
class A {
public:
void display() {
cout << “Base class A display()” << endl;
}
};

// Base class B
class B {
public:
void display() {
cout << “Base class B display()” << endl;
}
};

// Derived class inheriting from A and B
class Derived : public A, public B {
public:
void show() {
cout << “Derived class show()” << endl;
}
};

int main() {
Derived obj;

// Uncommenting this line will result in an ambiguity error
// obj.display();

obj.A::display(); // Access A’s display()
obj.B::display(); // Access B’s display()
obj.show(); // Access Derived’s show()

return 0;

}

Write a program to demonstrate run time polymorphism

#include<iostream>

using namespace std;

// Base class with a virtual function
class Shape {
public:
// Virtual function
virtual void draw() {
cout << “Drawing a Shape” << endl;
}
};

// Derived class 1
class Circle : public Shape {
public:
// Override the virtual function
void draw() override {
cout << “Drawing a Circle” << endl;
}
};

// Derived class 2
class Square : public Shape {
public:
// Override the virtual function
void draw() override {
cout << “Drawing a Square” << endl;
}
};

int main() {
Shape* shapePtr;

Circle circle;
Square square;

// Point to a Circle object and call draw()
shapePtr = &circle;
shapePtr->draw(); // Calls Circle’s draw()

// Point to a Square object and call draw()
shapePtr = &square;
shapePtr->draw(); // Calls Square’s draw()

return 0;

}

Write a program to demonstrate function and class templates

#include<iostream>

using namespace std;

// Function template for finding the maximum of two values
template
T max(T a, T b) {
return (a > b) ? a : b;
}

// Class template for a generic Pair
template
class Pair {
public:
T1 first;
T2 second;

Pair(T1 f, T2 s) : first(f), second(s) {}

void display() {
cout << “Pair: (” << first << “, ” << second << “)” << endl;
}

};

int main() {
// Function template usage
int intResult = max(5, 3);
double doubleResult = max(3.14, 2.71);
char charResult = max(‘A’, ‘B’);

cout << “Max of integers: ” << intResult << endl;
cout << “Max of doubles: ” << doubleResult << endl;
cout << “Max of characters: ” << charResult << endl;

// Class template usage
Pair<int, double> pair1(10, 3.1415);
Pair<string, char> pair2(“Hello”, ‘X’);

cout << “Pair 1: “;
pair1.display();
cout << “Pair 2: “;
pair2.display();

return 0;

}

Write a program to demonstrate try, catch and throw statements.

#include<iostream>

using namespace std;

// Function that throws an exception
int divide(int a, int b) {
if (b == 0) {
throw “Division by zero is not allowed!”;
}
return a / b;
}

int main() {
int numerator, denominator;

cout << “Enter numerator: “;
cin >> numerator;

cout << “Enter denominator: “;
cin >> denominator;

try {
int result = divide(numerator, denominator);
cout << “Result of division: ” << result << endl;
} catch (const char* error) {
cerr << “Exception caught: ” << error << endl;
}

cout << “Program continues after exception handling.” << endl;

return 0;

}

Write a program to demonstrate multiple catch blocks

#include<iostream>

using namespace std;

// Function that throws exceptions of different types
void divideAndThrow(int numerator, int denominator)

{
if (denominator == 0) {
throw “Division by zero is not allowed!”;
} else if (denominator == 1) {
throw 1; // Throwing an integer
} else if (denominator == 2) {
throw ‘A’; // Throwing a character
}
}

int main() {
int numerator, denominator;

cout << “Enter numerator: “;
cin >> numerator;

cout << “Enter denominator: “;
cin >> denominator;

try {
divideAndThrow(numerator, denominator);
} catch (const char* error) {
cerr << “Exception caught (char*): ” << error << endl;
} catch (int error) {
cerr << “Exception caught (int): ” << error << endl;
} catch (char error) {
cerr << “Exception caught (char): ” << error << endl;
} catch (…) {
cerr << “Unknown exception caught” << endl;
}

cout << “Program continues after exception handling.” << endl;

return 0;

}

Write a program to demonstrate reading and writing text and binary files

#include <iostream>

#include <fstream>

#include <string>

using namespace std;

// Function to write text data to a file


void writeTextFile(const string& filename) {
ofstream file(filename);
if (!file.is_open()) {
cerr << “Error opening file for writing: ” << filename << endl;
return;
}

string data = “This is a text file example.\n”;
data += “You can write text data to a file using C++.\n”;

file << data;

file.close();

}

// Function to read and display text data from a file
void readTextFile(const string& filename) {
ifstream file(filename);
if (!file.is_open()) {
cerr << “Error opening file for reading: ” << filename << endl;
return;
}

string line;
while (getline(file, line)) {
cout << line << endl;
}

file.close();

}

// Function to write binary data to a file
void writeBinaryFile(const string& filename) {
ofstream file(filename, ios::binary);
if (!file.is_open()) {
cerr << “Error opening file for writing (binary): ” << filename << endl;
return;
}

int data[] = {1, 2, 3, 4, 5};
file.write(reinterpret_cast<char*>(data), sizeof(data));

file.close();

}

// Function to read and display binary data from a file
void readBinaryFile(const string& filename) {
ifstream file(filename, ios::binary);
if (!file.is_open()) {
cerr << “Error opening file for reading (binary): ” << filename << endl;
return;
}

int data[5];
file.read(reinterpret_cast<char*>(data), sizeof(data));

cout << “Binary Data: “;
for (int i = 0; i < 5; i++) {
cout << data[i] << ” “;
}
cout << endl;

file.close();

}

int main() {
// Text file operations
writeTextFile(“textfile.txt”);
cout << “Contents of textfile.txt:” << endl;
readTextFile(“textfile.txt”);
cout << endl;

// Binary file operations
writeBinaryFile(“binaryfile.bin”);
cout << “Contents of binaryfile.bin:” << endl;
readBinaryFile(“binaryfile.bin”);

return 0;

}

Write a program to demonstrate reading and writing objects

#include <iostream>

#include <fstream>

#include <string>

using namespace std;

// Define a class to represent an object
class Student {
public:
string name;
int age;

// Constructor
Student(const string& n, int a) : name(n), age(a) {}

// Default constructor
Student() : name(“”), age(0) {}

};

// Function to write objects to a binary file
void writeObjectsToFile(const string& filename, const Student students[], int numStudents) {
ofstream file(filename, ios::binary);
if (!file.is_open()) {
cerr << “Error opening file for writing objects: ” << filename << endl;
return;
}

// Write the number of objects first
file.write(reinterpret_cast<const char*>(&numStudents), sizeof(int));

// Write each object
for (int i = 0; i < numStudents; i++) {
file.write(reinterpret_cast<const char*>(&students[i]), sizeof(Student));
}

file.close();

}

// Function to read objects from a binary file
void readObjectsFromFile(const string& filename) {
ifstream file(filename, ios::binary);
if (!file.is_open()) {
cerr << “Error opening file for reading objects: ” << filename << endl;
return;
}

int numStudents;
file.read(reinterpret_cast<char*>(&numStudents), sizeof(int));

cout << “Reading ” << numStudents << ” objects:” << endl;

Student student;
for (int i = 0; i < numStudents; i++) {
file.read(reinterpret_cast<char*>(&student), sizeof(Student));
cout << “Student ” << i + 1 << “: Name: ” << student.name << “, Age: ” << student.age << endl;
}

file.close();

}

int main() {
// Create an array of Student objects
Student students[] = {Student(“Alice”, 20), Student(“Bob”, 22), Student(“Charlie”, 21)};
int numStudents = sizeof(students) / sizeof(Student);

// Write objects to a binary file
writeObjectsToFile(“student_objects.bin”, students, numStudents);
cout << “Objects written to student_objects.bin” << endl;

// Read objects from the binary file and display them
readObjectsFromFile(“student_objects.bin”);

return 0;

}

Write a program to demonstrate random access in files

#include<iostream>

#include<fstream>

#include<string>

using namespace std;

// Function to write data to a file
void writeDataToFile(const string& filename) {
ofstream file(filename, ios::binary);
if (!file.is_open()) {
cerr << “Error opening file for writing: ” << filename << endl;
return;
}

// Write sample data to the file
string data = “This is some sample data for random access.”;
file.write(data.c_str(), data.size());

file.close();

}

// Function to read data from a specific position in a file
void readDataFromFile(const string& filename, streampos position, int length) {
ifstream file(filename, ios::binary);
if (!file.is_open()) {
cerr << “Error opening file for reading: ” << filename << endl;
return;
}

// Seek to the specified position
file.seekg(position, ios::beg);

// Read and display data
char* buffer = new char[length];
file.read(buffer, length);
cout << “Data read from position ” << position << “: ” << string(buffer, length) << endl;

delete[] buffer;
file.close();

}

int main() {
const string filename = “random_access_file.bin”;

// Write data to the file
writeDataToFile(filename);

// Read data from specific positions
readDataFromFile(filename, 5, 10); // Read 10 characters starting from position 5
readDataFromFile(filename, 20, 15); // Read 15 characters starting from position 20

return 0;

}

Wanna learn more??

All of the above are important Lab questions of object-oriented programming in c++. Share towards your friends and also help them while coding.

Post a Comment

Previous Post Next Post