0% found this document useful (0 votes)
6 views

OOPS C++

Practical assignment
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)
6 views

OOPS C++

Practical assignment
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/ 12

NAME SRIKANTH DODDA

ROLL
2314104658
NUMBER

PROGRAM BACHELOR OF COMPUTER APPLICATIONS(BCA)

SEMESTER II

COURSE NAME OBJECT ORIENTED PROGRAMMING – C++

COURSE CODE DCA1203


QUES:- 1:-

ANS:- 1. A:- Function Overloading and Iteration Structures in C++

A. Function Overloading:
Function overloading in C++ allows the definition of multiple functions with the
same name in the same scope, differing in their parameter lists. This provides
flexibility in handling operations that share a conceptual purpose but operate on
different types or numbers of arguments.

Key Differences:

Scope:

Function Overloading: Occurs within the same class or scope.


Function Overriding: Takes place in the context of inheritance.
Parameters:

Function Overloading: Functions share the same name but have different
parameter lists.
Function Overriding: The overridden function in the derived class has the same
signature as the base class function.

Compile-time vs. Runtime:

Function Overloading: Resolved at compile-time based on the function signature.


Function Overriding: Resolved at runtime through dynamic polymorphism.
B. Iteration and Loop Structures:

i. For Loop:

#include <iostream>

int main() {
for (int i = 0; i < 5; ++i) {
std::cout <<

"Iteration: " << i << std::endl;


}

}
return 0;
}
The for loop initializes, checks a condition, and updates a variable in a concise
structure.

ii. While Loop:

#include <iostream>

int main() {
int i = 0;
while (i < 5) {
std::cout <<

"Iteration: " << i << std::endl;


++i;
}

++i;
}
retu
return 0;
}

The while loop repeats as long as a condition is true, providing flexibility in loop
control.

In Summary:
Both for and while loops are essential for iteration in C++, with for loops
offering a compact structure for a fixed number of iterations and while loops
providing flexibility for variable iterations based on a condition. Function
overloading and overriding enhance code expressiveness and reusability,
especially in object-oriented programming contexts. These concepts collectively
contribute to building robust and versatile C++ programs.

QUES:- 2:-

ANS:- 2:- Polymorphism is a fundamental concept in object-oriented


programming (OOP) that allows objects of different types to be treated as objects
of a common base type. It enables flexibility and extensibility in code, allowing a
single interface or method to represent various implementations. Polymorphism
can be achieved through different mechanisms, including compile-time
polymorphism (method overloading) and runtime polymorphism (method
overriding).

1. Compile-Time Polymorphism (Static Binding):

Method Overloading:
Method overloading is a form of compile-time polymorphism where multiple
functions in the same scope have the same name but different parameter lists. The
compiler determines which function to call based on the number or types of
arguments.

Example:

#include <iostream> double: " << num << std::endl;


}
class OverloadExample { };
public:
void print(int num) { int main() {
std::cout << "Printing OverloadExample obj;
integer: " << num << std::endl; obj.print(5);
} obj.print(3.14);

void print(double num) { return 0;


std::cout << "Printing }

In this example, the print method is overloaded to handle both integers and doubles,
demonstrating compile-time polymorphism.

2. Runtime Polymorphism (Dynamic Binding):

Method Overriding:
Method overriding is a form of runtime polymorphism where a base class method is redefined in
a derived class with the same signature. The actual function called is determined at runtime,
allowing flexibility in the implementation.

Example:
#include <iostream>

class Animal {
public:
virtual void sound() const {
std::cout << "Animal makes a sound" << std::endl;
}
};

class Dog : public Animal {


public:
void sound() const override {
std::cout << "Dog barks" << std::endl;
}
};

class Cat : public Animal {


public:
void sound() const override {
std::cout << "Cat meows" << std::endl;
}
};

int main() {
Animal* animalPtr;

Dog dog;
Cat cat;

animalPtr = &dog;
animalPtr->sound();

animalPtr = &cat;
animalPtr->sound();

return 0;
}

In this example, the sound method in the base class Animal is overridden in the derived classes
Dog and Cat. The appropriate method is called based on the actual type of the object during
runtime.

QUES:- 3:-
ANS:- Inheritance is a fundamental concept in object-oriented programming (OOP) that allows a
class (derived or child class) to inherit properties and behaviors from another class (base or
parent class). It facilitates code reusability, promotes the creation of a hierarchy of classes, and
enables the establishment of relationships between them.

Types of Inheritance:

i. Single Inheritance:
In single inheritance, a derived class inherits from only one base class.

Syntax: void eat() const {


std::cout << "Animal
cpp eats" << std::endl;
Copy code }
class Base { };
// Base class members
}; class Dog : public Animal {
public:
class Derived : public Base { void bark() const {
// Derived class members std::cout << "Dog barks"
}; << std::endl;
}
Example: };

#include <iostream> int main() {


Dog myDog;
class Animal { myDog.eat(); // Accessing
public: the eat() method from the base
class return 0;
myDog.bark(); }

ii. Multiple Inheritance:


In multiple inheritance, a derived class inherits from more than one base class.

Syntax: };
class Base1 {
// Base1 class members class Swimming {
}; public:
void swim() const {
class Base2 { std::cout << "Object
// Base2 class members swims" << std::endl;
}; }
};
class Derived : public Base1,
public Base2 { class FlyingFish : public
// Derived class members Flying, public Swimming {
}; // FlyingFish class members
Example: };

#include <iostream> int main() {


FlyingFish fish;
class Flying { fish.fly();
public: fish.swim();
void fly() const {
std::cout << "Object flies" return 0;
<< std::endl; }
}

iii. Multi-level Inheritance:


In multi-level inheritance, a derived class inherits from another derived class,
forming a chain.

Syntax: };
class Base { Example:
// Base class members
}; #include <iostream>

class Derived1 : public Base { class Animal {


// Derived1 class members public:
}; void eat() const {
std::cout << "Animal
class Derived2 : public eats" << std::endl;
Derived1 { }
// Derived2 class members };
// GermanShepherd class
class Dog : public Animal { members
public: };
void bark() const {
std::cout << "Dog barks" int main() {
<< std::endl; GermanShepherd myDog;
} myDog.eat();
}; myDog.bark();

class GermanShepherd : public return 0;


Dog { }

iv. Hierarchical Inheritance:


In hierarchical inheritance, multiple derived classes inherit from a common base
class.

Syntax: circle" << std::endl;


class Base { }
// Base class members };
};
class Square : public Shape {
class Derived1 : public Base { public:
// Derived1 class members void draw() const override {
}; std::cout << "Drawing a
square" << std::endl;
class Derived2 : public Base { }
// Derived2 class members };
};
int main() {
Example: Circle circle;
#include <iostream> Square square;

class Shape { Shape* shape1 = &circle;


public: Shape* shape2 = &square;
virtual void draw() const {
std::cout << "Drawing a shape1->draw(); // Calls the
shape" << std::endl; draw() method of the Circle
} class
}; shape2->draw(); // Calls the
draw() method of the Square
class Circle : public Shape { class
public:
void draw() const override { return 0;
std::cout << "Drawing a }

v. Hybrid Inheritance:
Hybrid inheritance is a combination of two or more types of inheritance (single,
multiple, multi-level, or hierarchical) within a program.

Example: rotate() const myCar.start();


{ // Accessing
#include std::cout the start()
<iostream> << "Electric method from
motor the Engine
class Engine { rotating" << class
public: std::endl;
} myCar.rotate(
void start()
}; ); //
const {
Accessing the
std::cout
class Car : rotate()
<< "Engine
public Engine, method from
started" <<
public the
std::endl;
ElectricMotor ElectricMotor
} class
}; {
// Car class
members return 0;
class }
ElectricMotor };
{
public: int main() {
void Car myCar;

QUES:- 4:-
ANS:- 4:- In C++, the fstream library provides classes that allow us to work
with files. Opening a file using a constructor simplifies the file handling process
by associating the file stream with a file during object creation. The constructors
of classes like ofstream (output file stream) and ifstream (input file stream) can be
used to open a file at the moment the object is created.

Example of Opening a File Using Constructor:

Let's consider an example where we want to open a file for writing using the
ofstream class constructor. The program will create an object of the ofstream
class, and during the creation of this object, the constructor will open the
specified file.

#include <iostream>
#include <fstream>

int main() {
// File name
const char* fileName = "example.txt";

// Creating an object of ofstream with the file name in the constructor


std::ofstream outFile(fileName);

// Checking if the file is successfully opened


if (outFile.is_open()) {
std::cout << "File opened successfully for writing." << std::endl;

// Writing data to the file


outFile << "Hello, this is an example of opening a file using a constructor."
<< std::endl;

// Closing the file


outFile.close();
std::cout << "File closed." << std::endl;
} else {
std::cerr << "Error opening the file for writing." << std::endl;
}

return 0;
}

In this example:

• The ofstream class is used to create an output file stream.


• The constructor of ofstream takes the file name as a parameter, opening the file
during object creation.
• The program checks if the file is successfully opened using the is_open() method.
• If the file is open, data is written to the file using the stream insertion operator
(<<).
• Finally, the file is closed explicitly using the close() method.
• This approach simplifies the process of file handling by combining the file
opening step with the object creation step. It is important to note that if the file
does not exist, the constructor will create it, and if it already exists, the
constructor will open it for further operations.

QUES:- 5:-
ANS:- 5 :- A. Class to Basic Type Conversion:

Class to basic type conversion, also known as conversion operators, allows a


user-defined class to be converted into a basic data type. This feature in C++
enables objects of a class to be used in a way that mimics the behavior of basic
data types.

Example:

#include <iostream> private:


float meters;
class Distance {
public: }
Distance(float m) : };
meters(m) {}
int main() {
operator float() const { Distance d(10.5);
return meters; float distanceInMeters = d;

In this example, the Distance class has a conversion operator (operator float()
const) that allows an object of the Distance class to be implicitly converted to a
float. This enables using a Distance object in a context where a float is expected.

B. Overloading a Unary Operator:

Overloading unary operators involves defining their behavior for user-defined


classes. Let's illustrate the procedure using the unary minus (-) operator as an
example.

Example:

#include <iostream> }
};
class MyNumber {
private: int main() {
int value; MyNumber num(5);
MyNumber negNum = -
public: num;
MyNumber(int v) : value(v)
{} std::cout << "Original
number: " << num.getValue()
MyNumber operator-() << std::endl;
const { std::cout << "Negated
return MyNumber(- number: " <<
value); negNum.getValue() <<
} std::endl;

int getValue() const { return 0;


return value; }

In this example, the unary minus operator (operator-() const) is overloaded for
the MyNumber class. When the unary minus is applied to a MyNumber object, a
new MyNumber object with the negated value is returned. The overloaded unary
minus operator allows users to apply the negation operation to objects of the
MyNumber class.

QUES:- 6:-
ANS:- 6;- A. File Mode:
File mode in C++ refers to the mode in which a file is opened, determining the
type of operations that can be performed on the file. When you open a file, you
specify a file mode to indicate whether you want to read, write, or both, and
whether the file should be created if it doesn't exist.

There are several file mode options available, and they are specified as a
combination of flags. The common file modes include:

• ios::in: Open file for reading.


• ios::out: Open file for writing.
• ios::binary: Treat the file as a binary file (useful for non-text files).
• ios::app: Append to the end of the file.
• ios::ate: Set the initial position at the end of the file.
• ios::trunc: If the file already exists, truncate its size to zero.

These modes can be combined using the bitwise OR operator (|) to open files in
multiple modes. For

example:

#include <fstream>

int main() {
// Open a file for writing and append to the end
std::ofstream outFile("example.txt", std::ios::out | std::ios::app);

// Your file operations here...

outFile.close(); // Close the file

return 0;
}

B. Vector and Deque Sequence Containers:

Vector:
A std::vector is a dynamic array that can grow or shrink in size. It is part of the
C++ Standard Template Library (STL) and provides dynamic array-like features
along with additional functionalities. Vectors offer constant-time random access
to elements and efficient insertion and deletion at the end.

Example:

#include <iostream> int main() {


#include <vector> // Creating a vector of
integers
std::vector<int> myVector; // Accessing elements
for (int i : myVector) {
// Adding elements to the std::cout << i << " ";
vector }
myVector.push_back(10);
myVector.push_back(20); return 0;
myVector.push_back(30); }

Deque:
A std::deque (double-ended queue) is a sequence container that allows fast
insertion and deletion at both ends. It provides constant-time random access and
is implemented as a dynamic array of fixed-size chunks. Deques are suitable for
scenarios where frequent insertion and deletion at both ends are required.

Example:
#include <iostream> myDeque.push_back(10);
#include <deque> myDeque.push_front(5);

int main() { // Accessing elements


// Creating a deque of for (int i : myDeque) {
integers std::cout << i << " ";
std::deque<int> myDeque; }

// Adding elements to the return 0;


deque }

Both std::vector and std::deque are versatile sequence containers with different
characteristics. The choice between them depends on the specific requirements of
the application, such as the type and frequency of operations performed on the
container.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy