oop
oop
3. Examiners are requested to award full marks if and only if the answer
written by the student is fully correct or almost correct.
Answer guidelines
Q.1)
( 0.5 marks may be awarded if the answer is partially correct or nearer to the model answer)
i)Encapsulation
ii) false (can be used as binary operator too)
vi)The process of acquiring properties and behavior of an existing class by another class is
known as inheritance
vii)unless the derived class defines all the virtual functions of the abstract base class then it can
not be instantiated.
ix)To prevent abnormal termination of the program such that the program can continue to run
based on user’s choice after displaying appropriate error message.
x)Access specifiers such as private, protected and public allow us the level of abstraction that
we want to achieve by allowing which other classes or functions can access the essential
features of agiven class.
xi)std indicates standard library of c++ package that contains definition of types, classes,
functions, variables, operators, manipulators etc. to be used within a c++ program.
xii) delete operator is used to deallocate memory space that was previously allocated to a
variable or array or an object using new operator.
Adv. – faster compilation and execution of the program due to absence of function call
overhead. Also saves the overhead of a return call from a function. (Marks distribution : 3 +
2)
Q.3) Student should write a program to demonstrate and distinguish between call by value and
call by address by writing two separate functions and calling them from main().
Q.4)Student should define two separate classes with atleast one-member variable in each class
and declare one friend function common to both the classes and define the friend function
outside the classes that accepts objects of both the classes as parameters to perform the value
swap within the friend function definition. In main(), friend function should be called after
creating one object each of the defined classes.
Q.5) Award full marks if proper examples are given else award partial marks based on
correctness and relevance of the code. Example program code should be preferred for defining
copy and move constructors within a class.
Q.6) 2 separate constructors should be defined within a class and demonstrate the differences
between the default and parameterized constructors by defining objects from main() function.
b)Student should define virtual function and its purpose. Then provide an example code by
writing a parent class with a virtual function and then, overriding it in a derived class. Then
write+the main() function and include required code to call the virtual function using base
class reference that points to the derived class object.
c)Limitations and restrictions of Interface : A topic that is related to Java language only . If
students try to answer the question award some marks based on correctness. Instead, if
student tries to explain abstract class of c++ with its limitations and restrictions then award
marks.
Q.9) a) Student should define two separate derived classes after defining a common base
class containing 3 variables with 3 different access specifiers. One class to be derived
using public inheritance mode and another with protected inheritance mode and
show which base class variables can be accessed in the derived classes by writing
proper code in main() function.
b)Student should define a base class with a member function and constructor. Should
define one derived class from the base class and override the inherited function.
Within the function definition student should call the base class version of the function
and add necessary code specific to the derived class version. In main(), student should
call the overridden function using derived class object. Should explain the reusability
featureof inheritance with respect to the written code.
Q.10)a) Student should explain by writing a sample program with a base class and a derived
class. In main(), necessary code should be written to demonstrate calling the
overridden function using base class reference that refers to an object of the derived
class.
b) Benefits: To achieve run time polymorphism using dynamic binding feature where
using a base class reference, different derived class specific versions of the overridden
virtual functions, defined in various derived classes, can be called using the same
function call statement to produce clean code.
Q.11)a) Stream class hierarchy should be drawn and brief purpose of each class should
written.
b)The purpose of both getline() and write() functions should be written and explained
with example program code.
CS/B.TECH(N)/EVEN/SEM-6/6602/2023-2024
MAULANA ABUL KALAM AZAD UNIVERSITY OF TECHNOLOGY, WEST BENGAL
Paper Code : OE-EC604C Object Oriented Programming
UPID : 006602
#include <iostream>
void incrementByValue(int x) {
x++; // Increment the parameter (copy)
}
int main() {
int num = 5;
incrementByValue(num); // Pass a copy of num
std::cout << "Value in main after call: " << num << std::endl; // Output: 5 (unchanged)
return 0;
}
4. Write a program to exchange values between two classes using friend function. [5]
Ans:- #include <iostream>
class ClassA {
private:
int value_a;
public:
ClassA(int val) : value_a(val) {}
// Friend function to exchange values with ClassB
friend void exchange(ClassA& obj1, ClassB& obj2);
void printValues(const ClassB& obj) const {
std::cout << "Value in ClassA: " << value_a << std::endl;
std::cout << "Value in ClassB: " << obj.value_b << std::endl;
}
};
class ClassB {
private:
int value_b;
public:
ClassB(int val) : value_b(val) {}
// Friend function declaration (optional, but good practice)
friend void exchange(ClassA& obj1, ClassB& obj2);
2/11
};
// Friend function definition (outside the class)
void exchange(ClassA& obj1, ClassB& obj2) {
int temp = obj1.value_a;
obj1.value_a = obj2.value_b;
obj2.value_b = temp;
}
int main() {
ClassA obj_a(10);
ClassB obj_b(20);
std::cout << "Before exchange:" << std::endl;
obj_a.printValues(obj_b);
exchange(obj_a, obj_b);
std::cout << "After exchange:" << std::endl;
obj_a.printValues(obj_b);
return 0;
}
5. What is Copy Constructor and Move Constructor? [5]
Ans:- Copy Constructor:
1.A copy constructor is used to create a new object as a copy of an existing object.
2.It takes a reference to an existing object of the same class as an argument and initializes the new object
with the values from the existing object.
3.This is helpful for creating deep copies of objects or passing objects by value while avoiding unintended
modifications to the original object.
Move Constructor (C++11 and later):
1.Introduced in C++11, a move constructor is used to efficiently transfer ownership of resources (like
memory or file handles) from one object to another.
2.It takes an rvalue reference (reference to a temporary object) of the same class as an argument and
"steals" the resources from the temporary object, leaving it in a valid but empty state.
3.Move constructors are often used in conjunction with move assignment operators (discussed later) to
optimize resource management and prevent unnecessary copying.
6. What are the differences between Default and parameterized constructor? [5]
Ans:- Default Constructor:
No arguments: A default constructor has no arguments in its parameter list.
Automatic creation: The compiler automatically provides a default constructor if you don't define any
constructor explicitly in your class.
Initialization: It typically initializes member variables to default values (0 for integers, null for pointers,
etc.). You can also define your own default constructor for custom initialization.
Example:
class MyClass {private:
int value;
public:
// Default constructor (implicitly provided by compiler)
MyClass() : value(0) {} // Can be customized for specific initialization
};
Parameterized Constructor:
Arguments: A parameterized constructor takes arguments in its parameter list, allowing you to specify
initial values for the object's data members during creation.
Explicit definition: You need to define a parameterized constructor explicitly in your class code.
Flexibility: It provides more control over object initialization by setting member variables based on the
provided arguments.
Example:
3/11
MyClass(int val) : value(val) {}
};
input/output (I/O) devices. Stream classes in C++ facilitate input and output operations on files and other
I/O devices. These classes have specific features to handle program input and output, making it easier to
write portable code that can be used across multiple platforms.
In this blog, we’ll be exploring four essential C++ stream classes:
1.istream
2.ostream
3.ifstream
4.ofstream
Object-oriented programming, such as C++, relies heavily on the concept of inheritance. Inheritance
allows a class to inherit properties from another class that has already been defined. Descendant classes
can then add their own unique properties, making them specializations of their parent class.
Take the stream class hierarchy as an example. In the diagram below (only a portion is shown), we can see
that ifstream is a specialization of istream. This means that an ifstream object is an istream object and
inherits all the properties of the istream class. Additionally, it adds some additional properties of its own.
The C++ stream class hierarchy consists of a number of classes that define and provide different flows for
objects in the class. The hierarchy is structured in a way that starts with the top class, which is the ios
class, followed by other classes such as the istream, ostream, iostream, istream_withassign, and
ostream_withassign classes.
The ios class is the parent class in the hierarchy and both the istream and ostream classes inherit from it.
These two classes together form the ios class, which is the highest level of the entire C++ stream class
hierarchy.
Other classes in the hierarchy provide functions for various operations, including assignment operations,
such as the _withassign classes.
1. The istream class
This class is a general-purpose input stream and is used to read input from various sources, including the
console and files. One example of an istream is cin, which is a commonly used input stream for reading
input from the console. The istream class provides a range of functions for handling characters, strings,
and objects, including get, getline, read, ignore, putback, and cin.
1
9/11
2
3
4
5
6
7
8
9 #include <iostream>
using namespace std;
int main()
{
char a;
cin.get(a);
cout << a;
return 0;
}
2. The ifstream class
When working with the ifstream class in your code, you may come across situations where you need to
read data from a file to proceed with your program. This is where file handling comes into play, and it
involves using stream classes to accomplish this task.
An ifstream object represents an input file stream, which is used to read data from a file. Since an
ifstream is a type of istream, any operations that can be performed on an istream can also be performed
on an ifstream.
One common example of an istream is cin, which is used for standard input. Therefore, any operations
that you can perform with cin can also be performed with an ifstream object.
To use ifstream (and ofstream) in your code, you need to include the fstream header by adding the
following line at the beginning of your program:
#include <fstream>
3. The ostream class
The ostream class is responsible for working with the output stream and provides all the necessary
functions for managing chars, strings, and objects such as put, write, cout etc.
1
2
3
4
5
6
7
8 #include <iostream>
using namespace std;
intmain()
{
char u;
cin.get(u);
cout.put(u);
}
4. The ofstream class
An ofstream is an output file stream, and works exactly like ifstreams, except for output instead of input.
Once an ofstream is created, opened, and checked for no failures, you use it just like cout:
1
2 ofstream fout( "outputFile.txt" );
fout << "The minimum oxygen percentage is " << minO2 << endl;
C++ streams are used in a wide variety of applications, from simple console programs to complex
software systems. Some common use cases for C++ streams include:
1.Reading and writing to files – C++ streams provide a convenient way to read and write data to and from
files. This can be used to create log files, read configuration files, and more.
2.Parsing input – C++ streams can be used to parse input data, such as reading data from a CSV file or
parsing command-line arguments.
3.Debugging – C++ streams can be used to output debugging information, such as the value of variables,
10/11
to the console or a file.
4.Network programming – C++ streams can be used to read and write data over a network connection,
such as when creating a client-server application.
(b) Why we use getline() and write () functions, explain with example? [5]
Ans:- getline()
Header: <string>
Purpose: Reads a line of characters from an input stream (typically cin) and stores it in a string object. It
stops reading when a delimiter character (usually newline '\n') is encountered or the end-of-file (EOF) is
reached.
Syntax:
std::istream& getline(std::istream& is, std::string& str, char delim = '\n');
Parameters:
ois: The input stream from which to read (usually cin for standard input).
ostr: The string object to store the extracted line.
odelim (optional): The delimiter character to stop reading at (default is newline '\n').
Example:
#include <iostream>#include <string>
int main() {
std::string name;
std::cout << "Enter your name: ";
std::getline(std::cin, name); // Read the entire line, including spaces
std::cout << "Hello, " << name << "!" << std::endl;
return 0;
}
write()
Header: <iostream> or <fstream> (for file streams)
Purpose: Writes a sequence of characters from a memory block to an output stream (typically cout for
standard output or a file stream).
Syntax (for ostream):
std::streamsize write(const char* s, std::streamsize n);
Parameters:
os: A pointer to the memory block containing the characters to write.
on: The number of characters to write (can be less than the actual length of the string).
Syntax (for ofstream):
Parameters (same as ostream):
os: A pointer to the memory block containing the characters to write.
on: The number of characters to write.
Return Value: Returns the number of characters successfully written, or a negative value on error.
Example (Writing to cout):
#include <iostream>
int main() {
const char* message = "This is a message to be written.\n";
std::cout.write(message, strlen(message)); // Write the entire message
return 0;
}
11/11