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

OOP

The document provides a comprehensive overview of C and C++, highlighting key differences such as object-oriented support, data encapsulation, and memory allocation. It includes code examples for file handling, calculating sums, and demonstrates concepts like function overloading, overriding, and the use of unions. Additionally, it discusses advanced topics like pure virtual functions, static members, and encapsulation in C++.

Uploaded by

z6ole
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

OOP

The document provides a comprehensive overview of C and C++, highlighting key differences such as object-oriented support, data encapsulation, and memory allocation. It includes code examples for file handling, calculating sums, and demonstrates concepts like function overloading, overriding, and the use of unions. Additionally, it discusses advanced topics like pure virtual functions, static members, and encapsulation in C++.

Uploaded by

z6ole
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

Q1. Differentiate between C and C++.

Ans:

C does no support polymorphism,


encapsulation, and inheritance C++ supports polymorphism, encapsulation,
which means that C does not and inheritance because it is an object oriented
support object oriented programming language.
programming.

C is (mostly) a subset of C++. C++ is (mostly) a superset of C.

Data and functions are separated in


Data and functions are encapsulated together in
C because it is a procedural
form of an object in C++.
programming language.

Built-in data types is supported in Built-in & user-defined data types is supported in
C. C++.

Function and operator overloading Function and operator overloading is supported by


is not supported in C. C++.

C is a function-driven language. C++ is an object-driven language

Functions in C are not defined


Functions can be used inside a structure in C++.
inside structures.

Namespace features are not Namespace is used by C++, which avoid name
present inside the C. collisions.

Standard IO header is stdio.h. Standard IO header is iostream.h.

Reference variables are not


Reference variables are supported by C++.
supported by C.
Q2 .C++ Program to Copy One File into Another File

// C++ Program to demonstrate


// copying the content of a .txt file
#include <fstream>
#include <iostream>
using namespace std;
int main()
{
string line;
// For writing text file
// Creating ofstream & ifstream class object
ifstream ini_file{
"original.txt"
}; // This is the original file
ofstream out_file{ "copy.txt" };
if (ini_file && out_file) {
while (getline(ini_file, line)) {
out_file << line << "\n";
}
cout << "Copy Finished \n";
}
else {
// Something went wrong
printf("Cannot read File");
}
// Closing file
ini_file.close();
out_file.close();
return 0;
}

Q3. A Write a program to calculate the sum of all odd numbers between 1 and 50
#include <iostream>

int main() {
int sum = 0; // initialize sum to 0
for (int i = 1; i <= 50; i += 2) { // iterate over odd numbers (increment by 2)
sum += i; // add each odd number to the sum
}
std::cout << "Sum of all odd numbers between 1 and 50: " << sum << std::endl;
return 0;
}

B How does function overriding differ from function overloading?


• Function Overloading: allows multiple functions to share the same name, but they
must have different parameters. It can occur without inheritance and happens at
compile time.
• Function Overriding: allows a method to be redefined with the same name and
signature in the inheriting class. It requires inheritance and happens at run time.
Key differences:
• Inheritance: Function overloading does not use inheritance, while function
overriding is achieved with the help of inheritance.
• Parameters: Function overloading allows functions to have the same name but
different parameters, while function overriding requires functions to have the same
name and signature.
• Time of occurrence: Function overloading happens at compile time, while function
overriding happens at run time.
• Scope: Function overloading occurs in the same scope, while function overriding
occurs in different scopes.
C Scope Resolution Operator?
The scope resolution operator in C++ is :: . It is used to identify and access variables,
functions, or classes defined in different scopes. The scope resolution operator helps
disambiguate identifiers, making code more organized and manageable.

Syntax of Scope Resolution Operator


scope_name :: identifier

#include <iostream>
int main() {
// Accessing cout from std namespace using scope
// resolution operator
std::cout << "GeeksforGeeks";
return 0;
}
D. Use of Unions in C++
In C++, a union is a special data type that allows multiple variables of different data types to
share the same memory location. This is achieved by declaring a union with multiple
members, each of a different data type. Only one member can be active at any given time,
and accessing one member will overwrite the values of the others.
Key Characteristics
1. Shared Memory Location: All members of a union share the same memory location.
2. Only One Active Member: At any given time, only one member of the union can be
accessed or modified.
3. Overwriting: Accessing one member will overwrite the values of the others.
Use Cases
1. Memory Efficiency: Unions can be used to conserve memory when working with
large structures or arrays, as only one member needs to be stored at a time.
2. Tagged Unions: Unions can be used to implement tagged unions, where a single
memory location is used to store different types of data, and a tag or discriminator is
used to determine which type is stored.
3. Variant Types: Unions can be used to implement variant types, where a single
memory
E. What is the difference between Structure and Union? Give suitable examples to
justify your answer?

Feature Structure Union

Memory Each member of a structure has its All members of a union share
Allocation own memory space. the same memory space.

The size of a structure is the sum of


The size of a union is the size
Size the sizes of its members (with
of its largest member.
padding).

Only one member of a union


All members of a structure can be
Data Storage can store a value at any given
accessed and stored simultaneously.
time.

Used when only one member is


Used when all members need to hold
Usage needed at a time to save
independent data.
memory.

All members are accessed Accessing one member affects


Access
independently. the value of other members.

Handling data that could take


Example Representing a record with multiple
different forms (e.g.,
Usage related fields.
typecasting).

Code Examples
Structure Example

#include <stdio.h>
struct Student {
int id;
float marks;
char name[20];
};

int main() {
struct Student s = {1, 92.5, "Alice"};
printf("ID: %d\n", s.id);
printf("Marks: %.2f\n", s.marks);
printf("Name: %s\n", s.name);
return 0;
}

Union Example
#include <stdio.h>

union Data {
int intVal;
float floatVal;
char charVal;
};

int main() {
union Data d;

d.intVal = 42; // Assign to intVal


printf("Integer: %d\n", d.intVal);

d.floatVal = 3.14; // Overwrites intVal


printf("Float: %.2f\n", d.floatVal);

d.charVal = 'A'; // Overwrites floatVal


printf("Character: %c\n", d.charVal);

// Accessing intVal now gives undefined behavior


return 0;
}
E. What is the difference between Pass by value and Pass by reference?

Feature Pass by Value Pass by Reference

A copy of the actual argument's value A reference to the actual argument


Definition
is passed to the function. is passed to the function.

The function works with a separate The function works directly with
Memory
copy, so changes do not affect the the original variable, so changes are
Usage
original variable. reflected.

Effect on The original variable remains The original variable can be


Original Data unchanged. modified.

Parameter Typically used for primitive types like Requires pointers (C/C++) or
Type int, float. references (C++, Python).

Used when you do not want to modify Used when you want to modify the
Use Case
the original variable. original variable or for efficiency.

F. Data hiding and Encapsulation?


Data Hiding and Encapsulation in C++: Data hiding and encapsulation are two fundamental
concepts in object-oriented programming (OOP) in C++.
• Data Hiding: Data hiding is a technique used to protect the data from unwanted access
and misuse. It is achieved by making the data private and providing public methods to
access and modify the data. This way, the data is hidden from the outside world and
can only be accessed through the provided methods.
• Encapsulation: Encapsulation is the process of wrapping up the data and the methods
that operate on the data into a single unit, called a class. This helps to hide the
implementation details of the class from the outside world and provides a clear
interface to interact with the class.
Key differences between Data Hiding and Encapsulation:
• Data hiding focuses on restricting access to the data, while encapsulation focuses on
wrapping up the data and methods into a single unit.
• Data hiding is a technique used to achieve encapsulation.
• In data hiding, the data is always private, while in encapsulation, the data can be
public or private.
Benefits of Data Hiding and Encapsulation:
• Improved data security and integrity
• Reduced coupling between classes
• Increased code reusability and maintainability
• Easier to modify and extend the code without affecting other parts of the program.

G .Use of Pure Virtual Functions?


Pure virtual functions in C++ are used to define an interface or an abstract base class, which
cannot be instantiated on its own but can be used as a blueprint for creating concrete derived
classes.
Declaring Pure Virtual Functions A pure virtual function is declared using the = 0 syntax at
the end of the function declaration. For example:

class Base {
public:
virtual void function_name() = 0;
};

Characteristics of Pure Virtual Functions


• A class with at least one pure virtual function is considered an abstract class.
• Abstract classes cannot be instantiated directly.
• Derived classes must override all pure virtual functions from the base class to become
concrete (instantiable) classes.
• Pure virtual functions can be used to define an interface or a contract between the
base class and its derived classes.
Use of Pure Virtual Functions
• Abstraction and Interface Definition: Pure virtual functions allow you to define an
abstract base class that serves as an interface or contract for derived classes.
• Polymorphism: Pure virtual functions enable dynamic binding or late binding, where
the actual function to be called is determined at runtime based on the type of object.
• Code Organization: Pure virtual functions help organize code by separating the
interface (defined in the abstract base class) from the implementation (provided by
derived classes).
• Flexibility: Pure virtual functions allow you to write more flexible and extensible
code.
• Reusability: Pure virtual functions enable code reuse by providing a common
interface for derived classes.
• Easier Maintenance: Pure virtual functions make it easier to modify or extend the
code without affecting the existing implementation.
#include <iostream>

using namespace std;

class Base {

public:

virtual void show() { // Virtual function

cout << "This is the Base class function." << endl;

};

class Derived : public Base {

public:

void show() override { // Overriding the virtual function

cout << "This is the Derived class function." << endl;

};

int main() {

Base* basePtr; // Base class pointer

Derived derivedObj; // Derived class object

basePtr = &derivedObj; // Pointing to derived class object

// Call the show() function using the base class pointer

basePtr->show(); // Output: "This is the Derived class function."

return 0;
}

H . Give any example showing classes and objects in C++?


Create a class called "MyClass":
class MyClass { // The class
public: // Access specifier
int myNum; // Attribute (int variable)
string myString; // Attribute (string variable)
};

Create an object called "myObj" and access the attributes:


class MyClass { // The class
public: // Access specifier
int myNum; // Attribute (int variable)
string myString; // Attribute (string variable)
};

int main() {
MyClass myObj; // Create an object of MyClass

// Access attributes and set values


myObj.myNum = 15;
myObj.myString = "Some text";

// Print attribute values


cout << myObj.myNum << "\n";
cout << myObj.myString;
return 0;
}

4. Discuss the concept of file input and output functions using File handling in
C++.?

File handling is used to store data permanently in a computer. Using file handling we
can store our data in secondary memory (Hard disk).
How to achieve the File Handling
For achieving file handling we need to follow the following steps:-
STEP 1-Naming a file
STEP 2-Opening a file
STEP 3-Writing data into the file
STEP 4-Reading data from the file
STEP 5-Closing a file.
File Input and Output Functions: The file input and output functions in C++ are used to
read from and write to files. These functions are:
• ifstream: used to read from a file
• ofstream: used to write to a file
• fstream: used for both reading and writing to a file

Steps for File I/O


1. Include the <fstream> header.
2. Create an object of the appropriate file stream class.
3. Open the file using the .open() method or by passing the file name to the constructor.
4. Perform file operations (read/write).
5. Close the file using .close().

Common File I/O Functions

Function Description

open(filename, mode) Opens a file with a specified mode.

close() Closes the file.

is_open() Checks if the file is successfully opened.

eof() Checks if the end of the file is reached.

getline() Reads a line of text from a file.

write() Writes data to a file in binary format.

read() Reads data from a file in binary format.

Modes of File Opening

Mode Description

ios::in Open for reading.

ios::out Open for writing.

ios::app Open for appending data at the end of the file.

ios::binary Open in binary mode.


Mode Description

ios::ate Open and move the file pointer to the end.

ios::trunc Truncate the file to zero length if it exists.

6. What is static data member and static member function?

In C++, a static data member is a variable that is shared by all objects of a class. It is
declared within the class definition using the static keyword, and its definition is
typically provided outside the class definition. A static data member has the following
characteristics:
1. Single copy: Only one copy of the static data member exists, shared among all objects
of the class.
2. No object association: Static data members are not associated with individual objects
of the class.
3. Accessed using class name: Static data members can be accessed using the class name
and the scope resolution operator (::).
4. Initialized only once: Static data members are initialized only once, when the program
starts.
Example:

class Counter {
public:
static int count; // declaration
};
int Counter::count = 0; // definition

int main() {
cout << Counter::count << endl; // prints 0
Counter obj1;
Counter obj2;
cout << Counter::count << endl; // still prints 0
return 0;
}

Static Member Function: A static member function is a function that is associated


with a class, rather than an object of the class. It is declared within the class definition
using the static keyword. A static member function has the following

characteristics:
1. No object association: Static member functions are not associated with individual
objects of the class.
2. Called using class name: Static member functions can be called using the class name
and the scope resolution operator (::).
3. Accesses only static members: Static member functions can access only static data
members and other static member functions.
4. Cannot access this pointer: Static member functions do not have access to
the this pointer, as they are not associated with an object.

Example:
class Math {
public:
static int add(int a, int b) { return a + b; }
};

int result = Math::add(2, 3); // calls static member function

You might also like