0% found this document useful (0 votes)
2 views35 pages

Oop QB Ans

The document outlines the rules and concepts of operator overloading in C++, including the necessity and benefits of overloading operators for user-defined types. It also explains friend functions, inheritance types, virtual functions, and access specifiers in inheritance, providing examples for clarity. Additionally, it discusses ambiguity in multiple inheritance and how to resolve it using scope resolution and virtual inheritance.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views35 pages

Oop QB Ans

The document outlines the rules and concepts of operator overloading in C++, including the necessity and benefits of overloading operators for user-defined types. It also explains friend functions, inheritance types, virtual functions, and access specifiers in inheritance, providing examples for clarity. Additionally, it discusses ambiguity in multiple inheritance and how to resolve it using scope resolution and virtual inheritance.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 35

Unit 3

What are the rules for overloading operators?

Rules for Operator Overloading

 Only existing operators can be overloaded. We cannot create a new operator

 Overloading operators are only for classes. We cannot overload the operator for built-in
data types.

 At least one operand must be a user-defined type.

 Some operators like ::, .?, sizeof, and typeid cannot be overloaded.

 Overloading does not change the number of operands.

 Cannot change operator precedence

 Some operators can only be overloaded as member functions .Operators like =, (), [],
and -> must be overloaded as member functions.

 Default arguments are not allowed in overloaded operator functions

• Binary operators overloaded through a member function take one explicit argument and
those which are overloaded through a friend function take two explicit arguments.

What is operator overloading? Why it is necessary to overload an operator?

Operator Overloading is a feature in C++ that allows you to redefine the meaning of an
existing operator

Necessary to Overload an Operator:

 Allows intuitive use of operators with user-defined types.


 Improves code readability and elegance.
 Makes expressions involving objects easier to understand.
 Supports operator chaining for cleaner syntax.
 Enables integration with C++ Standard Template Library (STL).
 Replaces complex function calls with familiar operators.
 Enhances maintainability of object-oriented code.
 Provides polymorphic behavior for operators.
 Helps achieve more natural and expressive programming.
 Maintains consistency with built-in type operations

Letter Stands For Meaning

O Object Handling Works naturally with user-defined objects.


Letter Stands For Meaning

P Polymorphism Gives different meaning to the same operator.

E Expression Clarity Makes expressions more readable and intuitive.

Simplifies code by removing complex function


R Readability
calls.

A Aesthetic Code Makes code cleaner and more elegant.

T Template/Library Use Allows use with STL containers (e.g., sort, set).

O Operator Chaining Enables chaining like a + b + c.

R Reusability Code becomes reusable across similar types.

Letter Stands For Meaning

S Simplified Syntax Operators feel natural to use.

M Maintainability Easier to maintain and debug.

A Avoids Confusion Custom meaning avoids ambiguous logic.

R Resembles Built-in Types Custom types act like built-in types.

Reduces effort in complex object


T Time-Saving
operations.

Explain friend function with example?

A friend function is a special function that is not a member of a class, but it is granted access
to the private and protected members of the class.

You declare a function as a friend using the friend keyword inside the class. It is commonly
used when two or more classes need to share private data with a common function.

Syntax:

class ClassName {

friend returnType functionName(arguments);

};

Example: Friend Function in C++

#include <iostream>
using namespace std;

class Box {

private:

int length;

public:

Box(int l) {

length = l;

// Declare friend function

friend void displayLength(Box b);

};

// Friend function definition

void displayLength(Box b) {

// Accessing private member directly

cout << "Length of the box is: " << b.length << endl;

int main() {

Box box1(15);

// Call the friend function

displayLength(box1);

return 0;

Give a programming example that overloads = = operator with its use

#include <iostream>

using namespace std;

class Student {

private:

int roll;
string name;

public:

Student(int r, string n) {

roll = r;

name = n;

// Overload the '==' operator

bool operator==(const Student& other) const {

return (roll == other.roll && name == other.name);

// Display student details

void display() {

cout << "Roll No: " << roll << ", Name: " << name << endl;

};

int main() {

Student s1(101, "Alice");

Student s2(101, "Alice");

Student s3(102, "Bob");

// Displaying students

cout << "Student 1: ";

s1.display();

cout << "Student 2: ";

s2.display();

cout << "Student 3: ";

s3.display();

// Using overloaded '==' operator

if (s1 == s2)
cout << "s1 and s2 are equal." << endl;

else

cout << "s1 and s2 are NOT equal." << endl;

if (s1 == s3)

cout << "s1 and s3 are equal." << endl;

else

cout << "s1 and s3 are NOT equal." << endl;

return 0;

Implement a C++ program to overload unary operator ++ to increment value of a variable

#include<iostream>

using namespace std;

class Counter {

int value;

public:

Counter() : value(0) {}

void display() { cout << "Value: " << value << endl; }

void operator++() {

++value;

};

int main() {

Counter c;

++c;

c.display();

return 0;

}
Write a program in C++ to use scope resolution operator.

#include <iostream>

using namespace std;

int x = 10; // Global variable

class Demo {

public:

int x; // Member variable

void setValues(int x) {

this->x = x; // Set member variable using 'this'

void showValues() {

cout << "Local (Member) x = " << x << endl;

cout << "Global x = " << ::x << endl; // Using scope resolution to access global x

};

int main() {

Demo d;

d.setValues(20);

d.showValues();

return 0;

Implement a C++ program for overloading + binary operator as a class member function to
perform addition of two complex numbers

#include <iostream>

using namespace std;

class Complex {

int real, imag;

public:

// Constructor with member initializer list

Complex(int r = 0, int i = 0) : real(r), imag(i) {}

// Overload '+' operator (improved: pass by const reference)

Complex operator+(const Complex& c) const {

return Complex(real + c.real, imag + c.imag);

// Display function

void display() const {

cout << real << " + " << imag << "i" << endl;

};

int main() {

Complex c1(2, 3), c2(4, 5), c3;

c3 = c1 + c2; // Using overloaded '+' operator

cout << "Sum of Complex Numbers: ";

c3.display();

return 0;

What is a friend function? What are the merits and demerits of using the friend function?

Friend Function - A friend function is a special function that is not a member of a class, but
it is granted access to the private and protected members of the class.

You declare a function as a friend using the friend keyword inside the class. It is commonly
used when two or more classes need to share private data with a common function.
. The function is defined anywhere in the program like a normal function.

Merits of friend function

1. While defining the friend function, there is no need to use the scope resolution
operator as friend keyword.

2. The friend can be defined anywhere in the program similar to normal function.

3. It can be invoked like a normal function without the help of any object.

4. A function may be friend of more than one class.

Demerits of friend function

1. The friend function is declared in the class but it, not a member function of the class.
To access the private data members of class it is necessary to create objects.

2. When a function is friend of more than one class then forward declaration of class is
needed

Which is operator overloading? Write steps to overload << & >>

operators.

#include <iostream>

using namespace std;

class Complex {

private:

int real, imag;

public:

// Constructor

Complex(int r = 0, int i = 0) : real(r), imag(i) {}

// Friend function for output

friend ostream& operator<<(ostream& out, const Complex& c);


// Friend function for input

friend istream& operator>>(istream& in, Complex& c);

};

// Output (<<) overloading

ostream& operator<<(ostream& out, const Complex& c) {

out << c.real << " + " << c.imag << "i";

return out;

// Input (>>) overloading

istream& operator>>(istream& in, Complex& c) {

cout << "Enter real and imaginary parts: ";

in >> c.real >> c.imag;

return in;

int main() {

Complex c;

cin >> c; // calls overloaded >>

cout << c << endl; // calls overloaded <<

return 0;

Implement a C++ program to overload unary operator-- to decrement value of a variable

#include<iostream>

using namespace std;

class Counter {

int value;
public:

Counter(int v) : value(v) {}

void operator--() {

--value;

void display() {

cout << "Value: " << value << endl;

};

int main() {

Counter c(5);

--c;

c.display();

return 0;

Implement a C++ program for overloading - binary operator as a friend function to


perform substraction of two complex numbers

#include<iostream>

using namespace std;

class Complex {

int real, imag;

public:

Complex(int r=0, int i=0) : real(r), imag(i) {}

friend Complex operator-(Complex, Complex);

void display() {

cout << real << " - " << imag << "i" << endl;

};
Complex operator-(Complex c1, Complex c2) {

return Complex(c1.real - c2.real, c1.imag - c2.imag);

int main() {

Complex c1(7, 4), c2(2, 3), c3;

c3 = c1 - c2;

c3.display();

return 0;

Unit 4

How to inherit base class as protected? Explain with example

In C++, when a class is inherited using the protected access specifier, it means:

 All public and protected members of the base class become protected in the derived
class.

 They are not accessible outside the derived class (i.e., from main or other classes).

 This is useful when you want to give limited access to base class features inside
derived classes, but hide them from external users.

#include<iostream>

using namespace std;

class Base {

public:

void greet() {

cout << "Hello from Base class!" << endl;

};

class Derived : protected Base {

public:

void callBase() {

greet(); // OK: greet() becomes protected in Derived


}

};

int main() {

Derived d;

d.callBase(); // ✅ Allowed

return 0;

Explain in short about different inheritance types with block diagram

🔹 Types of Inheritance:

1. Single Inheritance

2. Multiple Inheritance

3. Multilevel Inheritance

4. Hierarchical Inheritance

5. Hybrid Inheritance

Write a C++ program to implement concept of virtual function

Explain virtual base class & virtual function with example?

Virtual Base Class

A virtual base class is used in multiple inheritance to prevent duplicate copies of a base
class when it's inherited by multiple derived classes.

Virtual Function

A virtual function is a member function in the base class that you expect to be overridden
in derived classes. It enables runtime polymorphism.

#include<iostream>

using namespace std;

class Base {

public:

virtual void show() {


cout << "Base class\n";

};

class Derived : public Base {

public:

void show() override {

cout << "Derived class\n";

};

int main() {

Base* ptr;

Derived d;

ptr = &d;

ptr->show(); // Outputs: Derived class (due to virtual function)

return 0;

What does inheritance mean in C++? What are different forms of

inheritance? Give example of each.

Inheritance in C++ is a feature that allows a class (derived class) to acquire the properties
and behaviors (members) of another class (base class).

Types of Inheritance:

1. Single Inheritance

2. Multiple Inheritance

3. Multilevel Inheritance

4. Hierarchical Inheritance

5. Hybrid Inheritance

What is the ambiguity that arises in multiple inheritance? How it can be

overcome. Explain with example


Ambiguity arises in multiple inheritance when a derived class inherits from two or more
base classes that have common members (like same function or variable name).
The compiler gets confused about which base class member to use.

Example: Ambiguity in Multiple Inheritance

#include<iostream>

using namespace std;

class A {

public:

void show() {

cout << "Class A\n";

};

class B {

public:

void show() {

cout << "Class B\n";

};

class C : public A, public B {

// inherits show() from both A and B → ambiguity!

};

int main() {

C obj;

// obj.show(); // ❌ Error: Ambiguous

return 0;

Problem Solution

Same function in both base classes Use scope resolution operator

Diamond problem (duplicate base) Use virtual inheritance


Problem Solution

Solution: Scope Resolution Operator

int main() {

C obj;

obj.A::show(); // Calls show() of class A

obj.B::show(); // Calls show() of class B

return 0;

Discuss the role of access specifiers in inheritance and show their visibility

when they are inherited as public, private protected.

Access specifiers (public, protected, and private) control the visibility and accessibility of
class members after inheritance.

They affect:

1. Whether derived class can access base class members

2. Whether outside code can access inherited members

Specifier Accessible in Base Accessible in Derived Accessible Outside


Class Class Class

public ✅ Yes ✅ Yes (as-is) ✅ Yes (if public)

protected ✅ Yes ✅ Yes ❌ No

private ✅ Yes ❌ No ❌ No

Visibility Chart in Inheritance

Base Member Public Inheritance Protected Private


Access Inheritance Inheritance

public members public in derived protected in derived private in derived

protected members protected protected private


private members Not Inherited Not Inherited Not Inherited

Example: Public, Protected, and Private Inheritance

#include<iostream>

using namespace std;

class Base {

public:

int pub = 1;

protected:

int prot = 2;

private:

int priv = 3;

};

class PublicDerived : public Base {

public:

void show() {

cout << pub << " "; // ✅ Accessible

cout << prot << " "; // ✅ Accessible

// cout << priv; // ❌ Not Accessible

};

class ProtectedDerived : protected Base {

public:

void show() {

cout << pub << " "; // ✅ Accessible as protected

cout << prot << " "; // ✅ Accessible

}
};

class PrivateDerived : private Base {

public:

void show() {

cout << pub << " "; // ✅ Accessible as private

cout << prot << " "; // ✅ Accessible

};

int main() {

PublicDerived p1;

p1.show();

cout << p1.pub << endl; // ✅ OK (public)

return 0;

How to inherit a base class as protected? Explain it in Multiple base classes.

Syntax:

class Derived : protected Base { };

 All public and protected members of Base become protected in Derived.


 Private members of Base are not accessible in Derived.

Inheritance from Multiple Base Classes as protected

You can inherit from multiple base classes, each using the protected keyword.

🔍 Example:

#include<iostream>

using namespace std;

class A {

public:

void showA() {
cout << "Base A\n";

};

class B {

public:

void showB() {

cout << "Base B\n";

};

// Both base classes are inherited as protected

class C : protected A, protected B {

public:

void show() {

showA(); // ✅ Accessible: protected in C

showB(); // ✅ Accessible: protected in C

};

int main() {

C obj;

obj.show(); // ✅ OK

return 0;

Write a C++ program demonstrating use of the pure virtual function

with the use of base and derived classes.

#include<iostream>

using namespace std;


class Animal {

public:

virtual void sound() = 0; // Pure virtual function

};

class Dog : public Animal {

public:

void sound() {

cout << "Dog barks" << endl;

};

int main() {

Dog d;

d.sound();

return 0;

Explain function over loading & function overriding in detail.

Function Overloading

 Function overloading means having multiple functions with the same name but
different parameter lists in the same class.
 It is an example of compile-time polymorphism.
 Overloaded functions must differ by number or type of parameters (not just return
type).
 Improves code readability by using same function name for similar operations.
 Return type can be same or different.
 Achieved within the same scope (usually in the same class).

Example:

#include<iostream>

using namespace std;


class Print {

public:

void show(int a) {

cout << "Integer: " << a << endl;

void show(double b) {

cout << "Double: " << b << endl;

void show(string s) {

cout << "String: " << s << endl;

};

int main() {

Print p;

p.show(10);

p.show(3.14);

p.show("Hello");

return 0;

Function Overriding

Function overriding occurs when a derived class provides its own version of a base class’s
virtual function.

 Function overriding means a derived class provides a specific implementation of a


function that is already defined in the base class.
 It requires inheritance and the function in the base class must be declared virtual.
 The overriding function must have the same name, parameters, and return type.
 It is an example of runtime polymorphism.
 Allows dynamic binding using base class pointers or references.
 Helps to achieve runtime behavior changes based on the object type.

Example:

#include<iostream>

using namespace std;

class Animal {

public:

virtual void sound() {

cout << "Animal sound" << endl;

};

class Dog : public Animal {

public:

void sound() override {

cout << "Dog barks" << endl;

};

int main() {

Animal* a;

Dog d;

a = &d;

a->sound(); // Calls Dog's sound() due to overriding

return 0;

Unit 5
Explain any five differences between function overloading vs function templates

Feature Function Overloading Function Template

Definition Multiple functions with the same name Single function definition that works
but different parameter types with any data type

Compile Time Decision made at compile time Template expanded at compile time

Code May result in duplicate code Avoids code duplication


Duplication

Syntax Normal function syntax Uses template<typename T>

Flexibility Limited to types you define Works for any type automatically

Demonstrate a program to detect and catch divide by zero division error problem in C++

#include<iostream>

using namespace std;

int main() {

int a, b;

cout << "Enter numerator and denominator: ";

cin >> a >> b;

try {

if (b == 0)

throw "Division by zero error!";

cout << "Result: " << (a / b) << endl;

} catc h (const char* msg) {

cout << "Exception caught: " << msg << endl;

return 0;

Write a C++ program using function template to find the product of two integer or
floating-pointtype of data
#include<iostream>

using namespace std;

template <typename T>

T multiply(T a, T b) {

return a * b;

int main() {

cout << "Product of 3 and 4: " << multiply(3, 4) << endl;

cout << "Product of 2.5 and 4.2: " << multiply(2.5, 4.2) << endl;

return 0;

explain class template using multiple parameters?WAP in c++

A class template can take more than one type using multiple template parameters. This
allows you to create generic classes that work with multiple data types.

#include<iostream>

using namespace std;

template <class T1, class T2>

class Pair {

T1 first;

T2 second;

public:

void setValues(T1 a, T2 b) {

first = a;

second = b;

void showValues() {

cout << "First: " << first << ", Second: " << second << endl;

}
};

int main() {

Pair<int, float> p1;

p1.setValues(10, 5.5);

p1.showValues();

Pair<string, int> p2;

p2.setValues("Age", 25);

p2.showValues();

return 0;

Explain name space with example.

A namespace in C++ is used to avoid name conflicts by grouping variables, functions, or


classes under a specific name.
It helps when two or more code blocks have the same identifiers (names).

🔸 Why Use Namespace?

 Prevents name conflicts in large programs.

 Allows organizing code logically.

 Makes it easier to manage large projects.

🔹 Syntax:

namespace name {

// declarations

Example:

#include<iostream>

using namespace std;

namespace A {
void display() {

cout << "Inside Namespace A" << endl;

namespace B {

void display() {

cout << "Inside Namespace B" << endl;

int main() {

A::display(); // Calls display() from namespace A

B::display(); // Calls display() from namespace B

return 0;

what is stream? Explain types of streams available in C++.

In C++, a stream is an object used to perform input and output (I/O) operations.
Think of a stream as a flow of data between your program and a device (like keyboard,
screen, or file).

Types of Streams in C++:

C++ provides different streams for input and output, mainly divided into:

🔸 1. Input Stream (istream)

 Used for reading input.

 Example: cin (standard input stream)

int x;

cin >> x; // Reading input using input stream

🔸 2. Output Stream (ostream)

 Used for writing output.

 Example: cout (standard output stream)

cout << "Hello"; // Writing output using output stream


🔸 3. File Input Stream (ifstream)

 Used to read data from a file.

#include<fstream>

ifstream fin("data.txt");

🔸 4. File Output Stream (ofstream)

 Used to write data to a file.

#include<fstream>

ofstream fout("data.txt");

🔸 5. File I/O Stream (fstream)

 Used for both reading and writing to files.

#include<fstream>

fstream file("data.txt", ios::in | ios::out);

Stream Type Class Purpose

cin istream Input from keyboard

cout ostream Output to screen

ifstream istream Read from file

ofstream ostream Write to file

fstream iostream Read & write file

Compare late binding & early binding

Feature Early Binding Late Binding

Binding Time Compile Time Run Time

Speed Faster Slower (slightly)

Flexibility Less flexible More flexible


Uses virtual? No Yes

Common Use Function overloading Runtime polymorphism

Function Type Normal functions Virtual functions

Unit 6

What is File Mode? Explain any four modes supported by C++.

In C++, file mode determines how a file is opened and how data is read from or written to
the file. File modes are defined using constants in the ios (input/output stream) class.

File modes are used with file streams like ifstream, ofstream, and fstream to specify whether
a file is to be opened for:

 reading,

 writing,

 appending,

 in binary mode, etc.

These modes can be combined using the bitwise OR operator (|).

📚 Common File Modes in C++

1. ios::in (Input Mode)

 Opens the file for reading.

 Used with ifstream or fstream.

 If the file does not exist, opening fails.

ifstream file("data.txt", ios::in);

2. ios::out (Output Mode)

 Opens the file for writing.

 If the file exists, its content is erased.

 If it doesn’t exist, a new file is created.

ofstream file("output.txt", ios::out);

3. ios::app (Append Mode)


 Opens the file in append mode.

 New data is written at the end of the file.

 Previous content is not deleted.

ofstream file("log.txt", ios::app);

4. ios::binary (Binary Mode)

 Opens the file in binary format (not plain text).

 Used when reading or writing binary files (images, audio, etc.).

 Must be used with read() or write().

fstream file("image.jpg", ios::in | ios::binary);

✅ Other Modes (Briefly Mentioned)

 ios::ate – Move the file pointer to the end of file upon opening, but allows
reading/writing anywhere in the file.

 ios::trunc – Truncates the file to zero length if it already exists (used with ios::out).

✅ Combining Modes

You can combine multiple modes using the | operator:

fstream file("data.txt", ios::in | ios::out);

This line opens the file for both reading and writing.

Mode Purpose

ios::in Open file for reading

ios::out Open file for writing (overwrite)

ios::app Append to the end of file

ios::binary Open file in binary mode

ios::ate Move pointer to end after opening

ios::trunc Delete content if file exists

Explain error handling during file operations.


When working with files in C++, it is important to handle file-related errors properly to avoid
unexpected behavior, crashes, or data loss. C++ provides built-in ways to detect and manage
errors during file operations.

📌 Common File Errors

1. File not found

2. File failed to open

3. Read/write failure

4. Reached end of file unexpectedly

5. File permission errors

✅ How to Handle File Errors in C++

C++ uses stream state functions to detect file I/O problems:

1. fail()

 Returns true if a file operation fails (e.g., open, read, write).

 Example: File could not be opened.

2. eof()

 Returns true when the end-of-file (EOF) is reached.

3. bad()

 Returns true when a serious error occurs (e.g., disk failure).

4. good()

 Returns true if no errors have occurred; the stream is fine.

5. is_open()

 Checks if the file is successfully opened.

Functio Purpose
n

fail() Returns true if operation failed (e.g., open)

eof() Returns true if end of file reached

bad() Returns true if a serious error occurred


good() Returns true if everything is fine

clear() Clears error flags

What is the difference between opening a file with constructor function and opening a file
with open () function

Feature / Aspect File Constructor open() Function

Definition Time File is opened when the object File is opened explicitly later using the
is created (instantiated). open() function.

Syntax ofstream file("data.txt"); ofstream file; file.open("data.txt");

Flexibility Less flexible — one file per More flexible — same object can open
object at a time. multiple files.

Use Case Best when file name is known Ideal when file name is dynamic (runtime
at compile time. input).

Multiple Files with Not possible; new object Possible — close one file and open another
One Object needed for each file. using same object.

Clarity / Brevity Shorter, cleaner syntax. Slightly more code, but allows more
control.

File Opening Mode Can use modes like ios::app, Can use the same modes when calling
Support ios::binary, etc. open().

Error Checking Slightly harder to handle Easier to check file open status (e.g., if (!
errors. file) check).

Real-life Example Writing a log to a known file Choosing a file based on user input (cin >>
(log.txt) filename;)

Changing File Mid- Not possible with constructor. Possible — close and open different files
Program with same object.

Write a program using the open ( ), eof ( ) & getline ( ) functions to open

& read file contents line by line.

#include<iostream>

#include<fstream>
#include<string>

using namespace std;

int main() {

ifstream file;

string line;

// Open the file using open()

file.open("sample.txt");

if (!file.is_open()) {

cout << "Error: File could not be opened!" << endl;

return 1;

// Read file line by line using getline()

while (!file.eof()) {

getline(file, line);

if (file.good()) {

cout << line << endl;

file.close(); // Close the file

return 0;

Explain file functions for text file and binary file operations

1. Text File Operations

These deal with reading and writing data in human-readable format.

2. Binary File Operations

These handle raw byte data and are used for non-text data (e.g., images, structures, etc.).

Common File Stream Classes


Class Description

ifstream Input file stream (for reading)

ofstream Output file stream (for writing)

fstream For both reading and writing

📘 File Functions for Text Files

Function Purpose

open("file.txt") Opens a text file

close() Closes the file

getline() Reads a line from text file

<< and >> Input/output operators

is_open() Checks if file is open

eof() Checks if end of file reached

fail() Checks if operation failed

💾 File Functions for Binary Files

Function Purpose

write((char*)&obj, sizeof(obj)) Writes binary data

read((char*)&obj, sizeof(obj)) Reads binary data

open("file.dat", ios::binary) Opens file in binary mode

Summary: Difference Between Text & Binary File Functions

Feature Text File Functions Binary File Functions

Data format Human-readable Raw byte stream

Read/Write <<, >>, getline() read(), write()


method

Usage Logs, notes, config Images, videos, records, structs

Explain the role of seekg(), seekp(), tellg(), tellp(), function in the


process of random access in a file.

🔹 seekg() – Set Input (get) Pointer

 Used with ifstream or fstream (in input mode).

 Moves the read pointer (get pointer) to a specified position.

Syntax:

file.seekg(offset, direction);

Example:

file.seekg(5, ios::beg); // Move to 5th byte from beginning

🔹 seekp() – Set Output (put) Pointer

 Used with ofstream or fstream (in output mode).

 Moves the write pointer (put pointer) to a specified position.

Syntax:

file.seekp(offset, direction);

Example:

file.seekp(0, ios::end); // Move to end of file

🔹 tellg() – Get Input (get) Pointer Position

 Returns the current position of the get pointer (read pointer).

Example:

int pos = file.tellg(); // Stores current read position

🔹 tellp() – Get Output (put) Pointer Position

 Returns the current position of the put pointer (write pointer).

Example:

int pos = file.tellp(); // Stores current write position

🧠 Directions Used

 ios::beg → from beginning


 ios::cur → from current position

 ios::end → from end of file

 Summary Table
Function Purpose Used For
seekg() Move get pointer Reading
seekp() Move put pointer Writing
tellg() Get get pointer pos Reading
tellp() Get put pointer pos Writing

write a program using put() to write characters to a file until user

enters a dollar sign

#include<iostream>

#include<fstream>

using namespace std;

int main() {

ofstream file("output.txt"); // Open file for writing

char ch;

cout << "Enter characters (end with $): ";

while (cin.get(ch)) {

if (ch == '$')

break;

file.put(ch); // Write character to file

file.close(); // Close the file

cout << "Data written to file successfully." << endl;

return 0;

Demonstrate a C++ program to create and write to .txt file with open() function to write
string “welcome”

#include<iostream>
#include<fstream>

using namespace std;

int main() {

ofstream fout;

fout.open("welcome.txt");

fout << "Welcome";

fout.close();

cout << "File written successfully.\n";

return 0;

You might also like