[go: up one dir, main page]

0% found this document useful (0 votes)
8 views18 pages

IA-DCA1210 - Object-Oriented Programming Using

The document discusses key programming concepts in C++ including the differences between procedural and object-oriented programming, the use of inline functions, exception handling, streams for I/O operations, access specifiers, and operator overloading. It highlights the advantages of C++'s object-oriented features such as encapsulation, modularity, and code reusability. Additionally, it provides examples and explanations of how these concepts improve code efficiency and maintainability.
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)
8 views18 pages

IA-DCA1210 - Object-Oriented Programming Using

The document discusses key programming concepts in C++ including the differences between procedural and object-oriented programming, the use of inline functions, exception handling, streams for I/O operations, access specifiers, and operator overloading. It highlights the advantages of C++'s object-oriented features such as encapsulation, modularity, and code reusability. Additionally, it provides examples and explanations of how these concepts improve code efficiency and maintainability.
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
You are on page 1/ 18

INTERNAL ASSIGNMENT

NAME ARYAN SINGH

ROLL NUMBER 2414502742

PROGRAM BCA

SEMESTER 2nd

COURSE NAME Object-Oriented Programming using


C++

CODE DCA1210

SESSION 2025
SET – I
Answers . (1)
Differences Between Procedural Programming in C and Object-
Oriented Programming in C++.
In the world of programming, two major paradigms have had the most
influence : Procedural Programming (C) and Object-Oriented
Programming (C++). Both languages are powerful, but they manage
code and data.
C language, developed in the 1970s, follows the procedular
programming approach. This means the code is written as a sequence
of steps using functions – following a top-down structure. In this
paradigm, data and logic are handled separately. Functions operate on
the data , but the data isn’t well proctected – especially when using
global variables, any function can accidentally modify the data.
Which can lead to errors.
On the other hand, C++, developed by Bjarne Stroustrup in the 1980s,
follows the object-oriented programming model, the program is
divided into smaller units called objects. Each object contains its own
data and the functions that operate on it. This concept is called
Encapsulation. Apart from that, C++ supports other powerful
features like Inheritance, Polymorphism, and Abstraction, which
make the code reusable, easier to maintain, and more secure.
Comparison Table: C vs C++

Feature C (Procedural) C++ (Object-


Oriented
Paradigm Procedural Object-oriented
programming programming
Approach Top-down Bottom-up

Focus Functions and Objects and classes


procedures
Data Security Low-data can be High-encapsulated
accessed globally within objects
Code Reusability Limited High-through
inheritance
Polymorphism Not supported Supported
Support (function/operator
overloading)
Real-world Difficult Natural-models real-
Mapping world entities
Extensibility Difficult to extend Easy to extend using
classes
Input/Output Uses printf,scanf Uses cin,cout

For example, if youre building a Bank Account system, in C you’d


write separate functions like create_account() , deposit() ,
withdraw() . and manage the data using structures. But in C++ , you
can create a class called Account that holds both data (like name and
balance) and functions (like deposit and withdraw) – all within one
unit.
This makes the code modular, reusable, and secure. If you later need
to add new features like SavingAccount or CurrentAccount , you
can simply extend the Account class using inheritance – avoiding
rewriting the existing code.
Couclusion
Both C and C++ are powerful programming languages, but C++’s
object-oriented model is better suited for large-scale projects.
Thanks to features like modularity, encapsulation, and code reuse,
C++ is widely used in modern development – especially for
applications like game development , GUI software, and real-world
simulations.

Answers . (2)
Inline Function in C++ and its Advantages
In C++, an inline function is a special type of function where the
compiler replaces the function call with the actual code of the
function during compilation. This is different from regular functions,
where the function’s code is stored.
To declare an inline function, the keyword inline is used before the
function definition. For example:

cpp

Inline int add(int a, int b) {


Return a + b;
}

Whenever this function is called in the program, like add(5, 3), the
compiler will replace it with 5 + 3 directly in the code – instead of
jumping to the function and returning the result. This process is know
as inline expansion.
However, it’s important to understand that using inline is only a
request to the compiler. The compiler can choose to ignore it,
especially if the function is too complex or involves loops, recursion,
or static variables.

Advantages of Inline Functions


1 . Faster Execution (Reduces Function Call Overhead)
One of the biggest benefits of using inline functions is that they
eliminate the overhead of a function call. In regular functions, the
control jumps to the function definition, executes it, and then returns.
This process takes time, especially when the function is called
frequently. Inline functions avoid this jump and make the code run
faster.
2 . Improves Performance in Small Functions
Inline functions are ideal for small, frequently used functions – like
mathematical operations (e.g., square(x) , add(a, b) ). Since their
code is short, replacing the function call with the actual code saves
time and doesn’t bloat the program much.
3 . Saves Memory in Recurring Calls
In normal functions, every time a function is called, some memory is
used in the stack to handle parameters and return addresses. Inline
functions reduce this by directly embedding the code – leading to
better memory utilization for small operations.
4 . Makes Code More Readable and Maintainable
Using inline functions keeps the main code cleaner. You write the
logic once in the function and call it wherever needed, without
worrying about runtime jumps. This balances the benefits of function
modularity with runtime efficiency.
When Not to Use Inline Functions
While inline functions sound great, they should not be used
everywhere. If the function is large or used in multiple places, inlining
can lead to code duplication, which increases the size of the binary
file (code bloat). This can negatively affect performance, especially
in embedded systems or memory-constained environments.
Also, functions involving loops, recursion, or static variables are
generally not inlined by the compier, even if marked as inline.

Conclusion
In summary, an inline function is a smart feature in C++ that helps
reduce function call overhead by expanding the function code directly
at the point of use. When used wisely – especially for short,
frequently called functions – inline functions can significantly
improve performance while keeping code clean and maintainable.
But like all tools, they should be used with care to avoid increasing
the size of the final program unnecessarily.

Answers . (3)
Excepetion Handling in C++ - Concept, Necessity, and Role of try,
throw, and catch
In real-world programming, it is common to encounter unexpected
situations like division by zero, file not found, or memory allocation
failure. If these runtime errors are not handled properly, the entire
program can crash. Expection handling in C++ offers a clean and
structured way to deal with such errors – allowing programs to
respond gracefully without terminating abnormally.
What is Expection Handling?
Expection handling is a feature in C++ that allows the program to
detect, throw, and catch errors during execution. Instead of checking
for errors using lengthy conditional statements, C++ allows
programmers to isolate error-prone code and handle it separately
using a special structure. This not only keeps the code clean but also
improves reliability.
When an error occurs, an ecception is “thrown” from the place where
the issue occurred and is “caught” by a handler that knows how to
deal with that specific type of error.
The Roles of try, throw, and catch
C++ implements expection handling through three main keywords:
try, throw, and catch.
1. try block
The code that might generate an exception is placed inside the
try block. It acts as a warning to the compiler that something
inside might go wrong.

cpp

Try {
// risky code here
}

2. throw statement
If an error is detected, the program uses throw to singal that an
exception has occurred. This transfers control to appropriate
catch block.
cpp

Throw “Division by zero!”;

3. catch block
The catch block receives the thrown exception and handles it. It
follows immediately after the try block.

Cpp

catch (const char* msg) {


cout << “Error: ” << msg;
}

Here’s a complete example:

cpp

try {
int a = 10, b = 0;
if (b == 0)
throw “cannot divide by zero!”;
cout << a / b;
}
Catch (const char* error) {
Cout << errors;
}

Instead of crashing, the program prints an error message when


division by zero is attempted.
Why Is Exception Handling Necessary?
(i) Graceful error handling: Instead of crashing, the
program can display user-friendly error messages.
(ii) Cleaner code: Keeps error-handling code separate from
main logic.
(iii) Supports modular programming: Each function can
manage its own exceptions without affecting the rest of the
program.
(iv) Improved debugging and reliability: Developers can
catch and log specific types of errors for easier debugging.

Conclusion
Exception handling is essentaial for developing reliable and stable
software. In C++, the try, throw, and catch mechanism provides a
powerful and elegant way to manage runtime errors. By using this
structured approach, developers can buildcapplications that handle
problems smoothly without crashing, improving the overall user
experience and robustness of the code.

SET – II
Answers . (4)
Basic Programming Using Streams in C++
In C++, streams are used to perform input and output (I/O)
operations. A stream can be thought of as a flow of data – either into a
program (input) or out of it (output). C++ provides a powerful set of
I/O capabilities through the use of stream classes, defined in the
<iostream>, <fstream>, and <sstream> headers.
What is a Stream?
A stream in C++ is an abstraction that represents a device (like a
keyboard, file, or monitor) from which data flows to the program or to
which flows from the program. They key idea is that a program does
not need to worry about how the data gets from one place to another –
it just reads from or writes to a stream.
Types of Streams
. cin - standard input stream (keyboard)
. cout - standard output stream (console)
. cerr - standard error output stream
. clog – standard log output stream
C++ also proides file-based streams using:
. ifstream – input file stream
. ofstream – output file stream
. fstream – input/output file stream

Steps in Stream-Based Programming


1. Creating a Stream Object
To work with files, you create an instance of ifstream, ofstream,
Or fstream.

Cpp

Ofstream myFile; // Output stream to a file

2. Connecting the Stream to a Source or Destination


This is usally done using the .open() function or constructor.

Cpp

myFile.open(“example.txt”); // Connect stream to file


3. Using the stream
Once connect, you can use stream operators (<< , >>) or
functions (getline, read, write) to perform input/output.

Cpp

myFile << “Hello, file!”; // Write to file

4. Disconnecting the Stream


Always close the stream after finishing to free up system
resources.

Cpp

myFile.close(); // Disconnected stream

Example Program: Writing to and Reading from a File


Cpp

#include <iostream>
#include <fstream>
Using namespace std;

Int main() {
// Creating and writing to a file
Ofstream outFile(“sample.txt”);
If (outFile.is_open()) {
outFile << “Hello from C++!” << endl;
outFile << “Writing to a file using streams.”;
outFile.close(); // Disconnect
}

// Reading from the file


Ifstream inFile(“sample.txt”);
String line;
If (inFile.is_open()) {
While (getline(inFile, line)) {
Cout << line << end1;
}
inFile.close(); // Disconnect
}

Return 0;
}

In this program:
>> A file named sample.txt is created and written using ofstream.
>> Then, ifstream is used to read its content back.
>> Both streams are properly closed after use.

Conclusion
Streams male I/O in C++ simple and abstract. Whether working with
the console or files, the same syntax and principles apply. Creating,
connecting, using, and disconnecting streams are key steps in
performing efficient I/O operations. This abstraction not only makes
code cleaner but also promotes flexibility and platform independence.

Answers . (5)
Access Specifiers in C++ and Their Usage with Examples
In C++, access specifiers play a crucial role in controlling the
visivility of class members (data and functions). They define how and
where class members can be accessed – whether from inside the class,
from derived classes, or from outside the class. These specifiers are
important for maintaining data security, encapsulation, and modularity
in object-oriented programming.
C++ provides three main access specifiers:
1. Private
. Members declared as private are accessible only within the same
class.
. They cannot be accessed directly from outside the class or even
from derived classes.
. This is the default access level in a class if no specifier is
mentioned.
cpp

Class Student {
private:
int rollNo;

public:
void setRollNo(int r) {
rollNo = r; // Allowed: access within the class
}

Int getRollNo() {
Return rollNo; // Allowed
}
};

Usage: rollNo is private and cannot be accessed directly using on


object like s.rollNo . Instead, we use public functions setRollNo()
and getRollNo() – this is a classic example of encapsulation.

2. Public
. Members declared as public are accessible from anywhere,
including outside the class.
. These are typically used for interface functions that allow
interaction with private data.
cpp

class Calculator {
public:
int add(int a, int b) {
return a + b;
}
};

Usage: An object of calculator can directly call add() :

cpp

calculator c;
cout << c.add(5, 3); // Output: 8

3. Proctected
. Protected members are similar to private, but they can also be
accessed by derived classes.
. These are used when you want to allow subclasses to use
certain internal data without exosing it publicly.
cpp

class Base {
protected:
int value:
}:\;

class Derived : public Base {


public:
void setValue(int v) {
value = v; // Allowed: accessed in derived class
}
Int getValue() {
return value;
}
};

Usage: Here, value is not accessible directly by the object, but the
derived class can access it internally.

Why Access Specifiers Matter?


. They enforce data hiding and encapsulation, two fundamental
principles of OOP.
. They allow class designers to protect internal details while exposing
only necessary functionality.
. By using access specifiers smartly, we reduce bugs and maintain
clean code architecture.

Conclusion
Access specifiers in C++ - private, public, and protected – define how
safely and clearly data is shared across different parts of a program.
While private protects sensitive data, public exposes functionality, and
proctected bridges the two in inheritance contexts. Using them
properly ensures robust, modular, and secure object-oriented design.
Answers . (6)
Operator Overloading in C++
In C++, operator overloading is a powerful feature that allows
developers to redefine the way operators work with user-defined data
types, such as classes and structures. Just like functions can be
overloaded to handle different types of inputs, operators can also be
customized to perform specific tasks when applied to objects.
The main idea is to make user-defined types behave more like built-in
types. For example,adding two integers using + is natural. But if you
have two complex numbers represented as objects, wouldn’t it be nice
to use + between them too? That’s exactly what operator overloading
allows.
What is Operator Overloading?
Operator overloading means redefining the behavior of an operator
(like +,-,*,==,etc.) so that it works with objects of a class. This helps
improve code readability, usability, and logic expression, making the
code feel more intuitive.

Syntax of Operator Overloading


To overload an operator, we use the operator keyword inside a class.
cpp

class ClassName {
public:
return_type operator op (arguments) {
// custom implementation
}
};

For example, to overload the + operator:


cpp

class Complex {
int real, imag;
public:
Complex(int r, int i) {
real = r;
imag = i;
}
Complex operator + (const Complex& obj) {
return Complex(real + obj.real, imag + obj.imag);
}

void display() {
cout << real << “+” << imag << “i” << end1;
}
};

Example Usage
cpp

Int main() {
Complex c1(2, 3), c2(4, 5);
Complex c3 = c1 + c2; // uses overloaded ‘+’ operator
c3.display(); // output: 6 + 8i
return 0;
}

In the example above, the + operator is redefined so that it can add


two complex number objects. Without operator overloading, you
would have to call a function like add(c1, c2), which is less intuitive
than simply writing c1 + c2.
Which Operators Can Be Overloaded?
Most of the built-in operators in C++ can be overloaded, such as:
. Arithmetic: +, -, *, /
. Comparison: ==, !=, <, >
. Assignment: =, +=, -=
. Stream: <<, >> (often overloaded for input/output)
However,some operators cannot be overloaded, like:
. :: (scope resolution)
. sizeof
. . (member access)

Why Use Operator Overloading?


. Improves readability: a + b is easier to understand than a.add(b)
. Makes classes more natural to use
. Supports polymorphism, making your class behave like built-in
types.

Conclusion
Operator overloading in C++ allows you to give intuitive meanings to
operators when they’re used with user-defined types. It enhances
readability and makes code more expressive, especially in classes like
Complex nembers, Vectors, Matrics, or Fractions. When used
carefully, operator overloading can make object-oriented programs
not just functional, but elegant and easy to maintain.
------------------------------------------------------------------------------------

You might also like