0% found this document useful (0 votes)
4 views14 pages

Objected Oreinted Programming Using C++ Assignment

The document discusses the differences between procedural programming in C and object-oriented programming in C++, highlighting aspects like programming approach, data handling, code reusability, and real-world problem modeling. It also explains inline functions, exception handling, stream operations, access specifiers, and operator overloading in C++. Each section includes definitions, advantages, examples, and conclusions to illustrate the concepts effectively.

Uploaded by

subhranshu pati
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)
4 views14 pages

Objected Oreinted Programming Using C++ Assignment

The document discusses the differences between procedural programming in C and object-oriented programming in C++, highlighting aspects like programming approach, data handling, code reusability, and real-world problem modeling. It also explains inline functions, exception handling, stream operations, access specifiers, and operator overloading in C++. Each section includes definitions, advantages, examples, and conclusions to illustrate the concepts effectively.

Uploaded by

subhranshu pati
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/ 14

Name Subhranshu Pati

Semester 2nd Sem


Roll Number 2414500297
Course Code & Name DCA1210–OBJECT-ORIENTED
PROGRAMMING USING
C++
Program Bachelors of Computer Application

Set-1

Q1. Describe the main differences between procedural programming in C and object-oriented
programming in C++.
Ans:-

Object-oriented programming versus procedural programming are two other programming


paradigms based on principles and directions of software development. C is procedural
language, whereas C++ can be used in object-oriented programming (OOP). Even though
C++ has been extended based on C, the language carries some advanced capabilities to deal
with complexity by using abstraction and modularity.

1. Programming Approach
• C (Procedural) uses top-down method, in which one breaks the program into
functions or procedures. The priority lies on the order of activities to undertake.
• C++ (OOP) is bottom up (it is based on objects and classes with data and behaviour
encapsulated).

2. Handling and Security of Data


• In C data is often global or function arguments. This reduces its security whereby any
functions can read and manipulates the data.

• C++ uses access specifiers (private, public, protected) to keep data in classes which
would result in data being more secure and safe.

3. Code Reusability
• C does not support reusability much. The code is typically recopied or reduplicated
when they need the same functionality in some other place.
• C++ is reusable because a single class can use the attributes and functions of another
one, so there is less redundancy.

4. Overloading of Function and Operators


• C does not have functional or operator overloading. The functions have to be given
unique names.

• The code written in C++ is more readable and flexible because of the functions
overloading (multiple functions with the same name and different parameters) and
operator overloading (assignment of specific behavior of operators).

5. Real- World Problem Modeling


• C is poor when it comes to modeling real objects because it lacks the notion of classes
and objects.

• C++ is created so that it is possible to implement the real-life situation in a very


simple way with the help of objects they are the representations of real things with
their qualities (data) and actions (functions).

6. Examples and Syntax


• In C, you will create such functions as main(), printf(), and scanf(), and organize code
through the use of conditionals and loops.

• When you use C++, you define classes, develop constructors, work with this pointer,
and have such capabilities as polymorphism or encapsulation.

Conclusion

To conclude, C is most applicable in small systematized programs that involved direct


manipulation of hardware or system level programming. C++, conversely, is stronger to
create large-scale applicative, maintainable, and reusability when real world modeling and a
modularity system is critical. C++ has object-oriented programming, which is more
abstraction, flexible and secure than procedural programming, C.
Q2. Define an inline function and explain its advantages.

Ans:-

A C++ inline function is a use of a special kind of function in which the compiler is asked to
substitute the corresponding actual code of the function during the compilation process,
instead of making a call to the function. This is achieved with the use of inline keyword prior
to the definition of function.

inline int add(int a, int b) {

return a + b;

As you invoke add(3, 5), inside add the compiler does not make a normal function call but
replaces add directly with 3 + 5. This spares us the overhead of pushing some variables to the
stack, jumping to the function, and returning back.

Positive aspects of Inline Functions

1. Improved Performance

Inline functions eliminate service overhead, particularly where the functions are small and are
frequently used. Time is saved because jumps and the mechanism of returns are avoided as
code is inserted right at the place of the call.

2. Faster Execution

Inline functions may also be faster, especially in loops or other performance-critical code,
since calling a function requires the overhead of placing the return address of the calling
program on the stack, and then returning to that program once the function returns to it. This
is useful in a system where speed is vital such as an embedded system or real-time software.

3. Question and Answer Style

Inline functions enable a programmer to have readable code and not to compromise their
performances. To avoid duplicating code you implement a function and yet can enjoy the
benefits of in-line replacement.

4. Code Reusability

Similar to other functions, inline functions advance code reuse. Once a logic is defined it can
be used many times, with performance next to direct code.
5. The Need to Use in Header Files

Inline functions are perfect in case of header files, since they do not result into the error of
multiple definition of the function during the linking phase. Defining a function as inline
enables its different occurrences within a translation unit in such a way that they do not
conflict on elements.

Restrictions and facts to mind

• The compiler can just discard the inline request when the function is too intricate (e.g.
loops, recursion or switch statements are involved).

• Over-inlining may cause a bigger binary (code bloat), particularly when the called
function is used frequently, causing worse performance because it overflows the
instruction cache.

• They are most appropriate to those small and straightforward tasks, such as getters,
setters and utilities calculations.

Conclusion
Inline functions provide the tradeoff between code performance and readability. With proper
usage, they can be used to remove useless overhead of making calls to functions, resulting in
quicker implementation. They however are suited to small functions whose speed is more
important than their size.

Q3. Explain the concept of exception handling in C++ and its necessity. Discuss the roles of
try, throw, and catch in the exception handling mechanism.

Ans:-
C++ exception handling is an important concept that enables a program to deal with
offensives or unforeseen situations (exceptions) in a polished way when in operation. The
program will be able to identify the error, process it according to pre-determined methods and
continue or shut down safely instead of crashing or giving inaccurate findings.

Reason of Exception Handling

Various reasons why errors may happen in the real world applications include:

• Division of zero
• Invalid input
• Can not locate file
• Memory allocation error
• Array out of range access

Absence of exception handling, it would be difficult to deal with such errors manually, and
the code will be complicated. Exception handling gives a well-staged, centered management
of the condition at programming run-time, and a readable, strong, and fault-tolerant code.

Exception handling Keywords

The three key words used by C++ in suppressing exceptions are:

1. try
2. throw
3. catch

1. try block

The try block contains the code that may cause an exception. It tells the compiler to watch
for exceptions in that block.
Example:

try {

int a = 10, b = 0;

if (b == 0)

throw "Division by zero!";

cout << a / b;
}
2. throw keyword

The throw statement is used to trigger an exception when an error is detected. It can throw
values of any type: built-in types, strings, or even objects of custom exception classes.
Example:

throw "Division by zero!";

3. catch block
The catch block is used to handle the exception thrown by the throw statement. It catches
the thrown value and processes it appropriately.

Example:

catch (const char* msg) {

cout << "Error: " << msg << endl;

Complete Example:

#include <iostream>

using namespace std;

int main() {

try {

int x = 10, y = 0;
if (y == 0)

throw "Cannot divide by zero.";

cout << x / y;

catch (const char* e) {

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

}
return 0;

Conclusion

Using exception handling is core in creating robust user friendly applications. Try, throw and
catch structure allows segregation of error-handling code and ordinary code which facilitates
debugging, maintenance, and extension of the program.

SET-2
Q4. Describe basic programming using streams in C++. Include the process of creating,
connecting, and disconnecting streams, and provide a simple example program.
Ans:-

Streams can be applied to do input and output (I/O) operations in C++. A flow is which is a
stream of bytes between a source that flows to one destination. The <iostream> and
<fstream> libraries of the Standard Template Library (STL) offer stream classes that are
highly dynamic, and highly flexible.

Types of Streams in C++

1. Input stream (istream) – for reading data (e.g., cin)

2. Output stream (ostream) – for writing data (e.g., cout)

3. File input stream (ifstream) – for reading from files

4. File output stream (ofstream) – for writing to files

5. fstream – for both reading and writing to files

Stream Operations

1. Creating Streams

To use file streams, include <fstream> and create objects of ifstream, ofstream, or fstream.

#include <fstream>

using namespace std;

ofstream outFile;
ifstream inFile;

2. Connecting Streams

You connect a stream to a file using the open() function or directly during object creation.

outFile.open("output.txt"); // Connecting output stream

inFile.open("input.txt"); // Connecting input stream

Or:

ofstream outFile("output.txt");
ifstream inFile("input.txt");

3. Disconnecting Streams

Always close the stream using the close() function to ensure proper file handling.
outFile.close();
inFile.close();

Simple Example Program:

#include <iostream>
#include <fstream>

using namespace std;

int main() {

string data;

// Step 1: Create and connect output stream


ofstream outFile("example.txt");
if (!outFile) {

cout << "Error opening file for writing." << endl;

return 1;

// Step 2: Write to file

outFile << "Hello, this is a sample text written to file.\n";


outFile.close(); // Disconnect stream

// Step 3: Create and connect input stream

ifstream inFile("example.txt");

if (!inFile) {

cout << "Error opening file for reading." << endl;

return 1;
}

// Step 4: Read from file


while (getline(inFile, data)) {

cout << "Read from file: " << data << endl;

inFile.close(); // Disconnect stream

return 0;

Conclusion

In C++, streams simplify a file and console console I/O operation. They deabstract low level
system calls and present high level, readable interface to manage data. The knowledge of
stream creation, connection and disconnection play a seminal role in the writing of effective
C++ programs.
Q5. What are access specifiers in C++? Provide examples to demonstrate the use of each
access specifier in a class.
Ans:-

In C++, the visibility and accessibility of class member variables and functions are decided
by the access specifiers of that class which defines the accessibility of the members to the rest
of the program. C++ three primary access specifications are:

1. Public
2. Private
3. Protected

Both accesses to the class members, internally and externally, or to derived classes are
controlled by each of them.

1. Public Access Specifier

• Members declared as public are accessible from anywhere in the program where the
object is visible.

• Commonly used for interface functions.

Example:

class Student {
public:

string name;
void display() {

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

};
Student s;

s.name = "John"; // Allowed

s.display(); // Allowed

2. Private Access Specifier

• Members declared as private are only accessible within the class.

• They cannot be accessed directly from outside the class.


• Ensures data hiding and encapsulation.
Example:

class Account {

private:

int balance;

public:

void setBalance(int b) {
balance = b;

int getBalance() {

return balance;

};
Account acc;

acc.setBalance(1000); // Allowed
cout << acc.getBalance(); // Allowed
// acc.balance = 500; // Not allowed (compilation error)

3. Protected Access Specifier

• Members declared as protected are like private for non-derived classes.


• However, they can be accessed by derived (child) classes.

• Useful in inheritance scenarios.

Example:

class Person {

protected:

string name;

};

class Employee : public Person {

public:

void setName(string n) {

name = n; // Allowed: derived class can access protected member

void showName() {
cout << "Employee Name: " << name << endl;

};

Employee emp;

emp.setName("Alice"); // Allowed

emp.showName(); // Allowed

// emp.name = "Bob"; // Not allowed: name is protected

Access Specifier Within Class Outside Class In Derived Class


Public Yes Yes Yes
Private Yes No No
Protected Yes No Yes
Conclusion:

Access specifiers in C++ help control access to class members, encouraging encapsulation,
data protection, and clean inheritance. Choosing the right specifier ensures better object-
oriented design.

Q6. Explain the concept of operator overloading in C++.

Ans:-

C++ operator overloading enables a developer to give a new meaning of the usage of
operators (such as +, -, *, etc.) when these operators are applied to user-defined data types
(such as classes and structures). It also adds readability to code and gives it the means of
using intuitive syntax with objects, as with basic data types.

What is the Reason to Use Operator Overloading?

In C++ built in operators (e.g. +, -, ==) operate on primitive data types. But in case of user-
defined types like objects, we might desire similar behaviour.
Example: There is Complex class for complex numbers. You can specify how it is to add two
complex numbers by means of the + operator.

Syntax of Operator Overloading

Operator overloading is done using a special function called an operator function. The
syntax is:

return_type operator symbol (arguments);

It can be defined either as a member function or a friend function.

Example: Overloading + Operator for a Complex Number Class

#include <iostream>

using namespace std;

class Complex {

private:

float real;

float imag;

public:
Complex() : real(0), imag(0) {}
Complex(float r, float i) : real(r), imag(i) {}

// Overloading '+' operator

Complex operator + (const Complex& obj) {


Complex temp;

temp.real = real + obj.real;

temp.imag = imag + obj.imag;

return temp;

void display() {
cout << real << " + " << imag << "i" << endl;
}

};

int main() {

Complex c1(3.5, 2.5), c2(1.5, 4.5);

Complex c3 = c1 + c2; // Calls operator+

c3.display(); // Output: 5 + 7i
return 0;

Operators That Can Be Overloaded

Almost all operators can be overloaded, including:

• Arithmetic operators: +, -, *, /

• Relational operators: ==, <, >

• Assignment: =
• Unary operators: ++, --

• Stream operators: <<, >> (for I/O)


Operators That Cannot Be Overloaded
• :: (scope resolution)

• . (member access)

• .* (pointer to member)

• sizeof
• typeid

Advantages of Operator Overloading

• Improves code readability.

• Allows natural syntax with objects.

• Makes user-defined types behave like built-in types.

Conclusion

Overloading of an operator makes object-oriented programming in C++ more powerful. It


does this by offering a flexible and intuitive user interface on operating with objects and
allows the operator to operate in a natural manner with user-defined types.

Please tell me, whether you would like some examples concerning other operators such as
==, <<, or [].

You might also like