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

oop

The document provides guidelines and instructions for examiners on how to check answer scripts for Object Oriented Programming at MAKAUT. It emphasizes the importance of marking answers based on relevance and correctness, and outlines specific criteria for awarding marks for very short, short, and long answer questions. Additionally, it includes sample questions and expected responses to ensure uniformity in evaluation.

Uploaded by

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

oop

The document provides guidelines and instructions for examiners on how to check answer scripts for Object Oriented Programming at MAKAUT. It emphasizes the importance of marking answers based on relevance and correctness, and outlines specific criteria for awarding marks for very short, short, and long answer questions. Additionally, it includes sample questions and expected responses to ensure uniformity in evaluation.

Uploaded by

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

Answer Script Checking Guidelines and Instructions

( as per discussions held with MAKAUT officials)


1. All Examiners are expected to read the answers properly and check
relevance with respect to the question asked and award marks
accordingly.

2. Examiners are suggested not to put a single small annotation (for


example a tick mark) for the entire answer and then award average
marks or below average marks. Justification must be made visible by
underlining irrelevant or wrong lines of answer or by putting question
marks. This applies to short answers or long descriptive answers both.

3. Examiners are requested to award full marks if and only if the answer
written by the student is fully correct or almost correct.

4. Examiners are requested to follow the model answer sheets provided by


the paper setter and the broad guidelines given by the Head examiner as
far as possible to maintain uniformity of evaluation.
5. Proper example code must by be written by the student in case it is
categorically asked for in a question for consideration of full marks.
Maulana Abul Kalam Azad University of Technology
Chief HE InstructionSheet, Even Semester, 2023-24
Paper Code:OE EC-604C Object Oriented Programming (UPID:6602)

Answer guidelines

GROUP-A (very short Answer type Questions)

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)

iii) insertion (<<) operator


iv)when an object is returned from a function by value, when an object is passed to a function
by value as an argument, when an object is constructed based on another object of the same
class.

v)operators that perform action on two operands. Such as + or * operators.

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.

viii)Text mode, - to read files as normal text

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.

GROUP-B (short answer type questions)


( part marking should be done based on correctness and relevance of the answer)
Full marks can only be awarded if the answer is fully correct
Q.2) Student should define inline() function. Should give an example code to define one inline()
function and call it from main().

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.

GROUP-C (Long answer type Questions)


( part marking should be done based on correctness and relevance of the answer)
Full marks can only be awarded if the answer is fully correct

Q.7)a)Student should demonstrate by writing program code to define two different


namespaces with the same variable name inside the defined namespaces and then
accessing those variables from main() function using scope resolution operator.

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.8) a)Example program code must be written to demonstrate operator overloading.


(ideally for one binary operator and one unary operator) with proper explanation.

b)Adv. Of operator overloading :


Simplified Syntax: Operator overloading allows programmers to use notation closer to
thetarget domain, making code more intuitive and expressive.

Consistency: It provides similar support to built-in types for user-defined types,


enhancing consistency and ease of use.
Easier Understanding:Operator overloading can make programs more accessible to
understand by allowing the use of familiar operators with user-
defined types, which can improve code readability and
maintainability.

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.

c) At least 5 differences must be written related to early and late binding.

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

Time Allotted : 3 Hours Full Marks :70


The Figures in the margin indicate full marks.
Candidate are required to give their answers in their own words as far as practicable

Group-A (Very Short Answer Type Question)


1. Answer any ten of the following : [ 1 x 10 = 10 ]
(I) Wrapping data and its related functions into a single entity is known as _____________.
Ans:- Encapsulation
(II) Scope resolution operator is a unary operator- true or false?
Ans:- True
(III) Which operator is overloaded for a cout object?
Ans:- <<
(IV) When a Copy Constructor may be called?
Ans:- When a new object is created from an existing object, as a copy of the existing object.
(V) Which is the correct example of a binary operator?
Ans:- +(adding two operands) requires two operands
(VI) What is Inheritance in C++?
Ans:- Inheritance is the concept of OOPs in which new classes are derived from existing classes in order to reuse the
properties of classes defined earlier.
(VII) Which problem may arise if we use abstract class functions for polymorphism?
Ans:- The undefined functions must be defined is a problem, because one may need to implement few undefined
functions from abstract class, but he will have to define each of the functions declared in abstract class. Being
useless task, it is a problem sometimes.
(VIII) By default, all the files in C++ are opened in _________ mode.
Ans:- Text Mode
(IX) Why do we need to handle exceptions?
Ans:- We need to handle exceptions in a program to avoid any unexpected behaviour during run-time because that
behaviour may affect other parts of the program. Also, an exception is detected during run-time, therefore, a
program may compile successfully even with some exceptions cases in your program.
(X) How access specifiers in Class helps in Abstraction?
Ans:- They allows us to show only required things to outer world
(XI) What is namespace std?
Ans:- The std is a short form of standard, the std namespace contains the built-in classes and declared functions.
(XII) What is a Delete Operator?
Ans:- The delete operator is used to deallocate memory that was previously allocated on the heap using new. It takes a
pointer to the memory to be deallocated as an argument. For example:
delete p; // Deallocates the memory pointed to by p

Group-B (Short Answer Type Question)


Answer any three of the following : [ 5 x 3 = 15 ]
2. Define inline function with proper example. what are the advantages of inline function? [5]
Ans:- An inline function is a function C++ that is marked with the inline keyword. The inline keyword is a
suggestion to the compiler that the function body should be inserted at each call site of the function. This
can improve the performance of the program by avoiding the overhead of a function call, which includes
things like saving the return address on the stack, pushing arguments onto the stack, jumping to the
function code, and then returning from the function.
Here is an example of an inline function that calculates the area of a rectangle:
inline int calculate_area(int width, int height) {
1/11
return width * height;
}
// Example usage of the inline function int area = calculate_area(5, 10);
Advantages of inline functions:
Improved performance: By avoiding the overhead of a function call, inline functions can improve the
performance of a program. This is especially beneficial for small functions that are called frequently.
Reduced code size: In some cases, inlining a function can reduce the code size of a program. This is
because the function body is only stored once in memory, instead of being stored in a separate function
code block.
3. Distinguish between call by value and call by address with an example. [5]
Ans:- Call by value and call by reference are two fundamental mechanisms for passing arguments to functions
in programming languages. Here's a breakdown of the key differences with an example:
Call by Value:
In call by value, a copy of the actual argument (the value of the variable) is passed to the function.
Any changes made to the parameter within the function do not affect the original variable in the calling
function.
This method is typically used for primitive data types like integers, floating-point numbers, and
characters.
Call by Reference:
In call by reference, a reference to the memory location of the actual argument (the address of the
variable) is passed to the function.
Modifications made to the parameter within the function directly affect the original variable in the
calling function because they both point to the same memory location.
This method is commonly used for complex data structures like arrays, objects, and structures.
Example:
Call by Value Example:

#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:

class MyClass {private:


int value;
public:
// Parameterized constructor with one argument

3/11
MyClass(int val) : value(val) {}
};

Group-C (Long Answer Type Question)


Answer any three of the following : [ 15 x 3 = 45 ]
7. (a) How we can disambiguate namespace by scope resolution operator? Explain with proper example. [4]
Ans:- If there present multiple namespaces in developed code, and functions or variables have the same name
across namespaces, the scope resolution operator helps clarify which namespace you're referring to.
namespace math {
int add(int a, int b) {
return a + b;
}
}
namespace science {
int add(int x, int y) {
return x * y; // Different functionality
}
}
int main() {
std::cout << "Math addition: " << math::add(5, 3) << std::endl;
std::cout << "Science addition (multiplication): " << science::add(5, 3) << std::endl;
return 0;
}

(b) What is a Virtual Functions in class? [6]


Ans:- In C++, virtual functions are a fundamental concept in object-oriented programming (OOP) that enable
runtime polymorphism. Here's a breakdown of what virtual functions are and how they work:
Concept:
A virtual function is a member function of a base class declared with the virtual keyword.
It serves as a prototype for derived classes to inherit and potentially redefine (override) to provide
specialized behavior.
Runtime Polymorphism:
When a virtual function is called through a base class pointer or reference that points to an object of a
derived class, the actual function implementation executed depends on the object's type at runtime.
This allows derived classes to provide their unique implementations for the inherited virtual function.
Benefits:
Flexibility: Virtual functions enable polymorphic behavior, making code more adaptable and reusable.
Maintainability: Code becomes easier to maintain as changes made to a virtual function in the base class
propagate to derived classes that override it, reducing the need for repetitive modifications.
Example:
Consider a base class Animal with a virtual function speak():
C++
class Animal {public:
virtual void speak() {
std::cout << "Generic animal sound" << std::endl;
}
};
(c) What are the Limitations and Restrictions of Interface ? [5]
Ans:- Interfaces in C++ offer a powerful tool for achieving abstraction and defining contracts for classes to
implement. However, they come with some limitations and restrictions to consider when designing your
program:
Limitations:
No Implementation: Interfaces only specify what a class should do, not how it should do it. This can be
beneficial for flexibility, but it also means you cannot provide default implementations for the methods
within the interface. All functionality must be implemented by the concrete classes.
Multiple Inheritance Issues: C++ doesn't directly support multiple inheritance of classes. While a class
can implement multiple interfaces, it can inherit from only one base class. This can limit code reusability
4/11
in certain scenarios where you might want to combine functionalities from multiple base classes.
Static Type Checking: C++ uses static type checking, which means the compiler verifies types at compile
time. Interfaces themselves don't have types, so the compiler cannot enforce type safety as strictly when
using interfaces compared to inheriting from classes.
Restrictions:
No Member Variables: Interfaces can only declare pure virtual functions (methods without
implementation). They cannot define member variables (data) as part of the contract. This can limit the
ability to specify data requirements for implementing classes.
No Constructors or Destructors: Interfaces cannot have constructors or destructors. These functionalities
are specific to class implementation and cannot be part of the abstract contract defined by an interface.
8. (a) Explain Operators Overloading in C++ with example [9]
Ans:- Operator overloading in C++ is a powerful feature that allows you to redefine the behavior of existing
operators (like +, -, *, /) for user-defined types (classes, structures). This makes your code more intuitive,
readable, and maintains a natural syntax when working with custom data types.
Why Use Operator Overloading?
Natural Syntax: You can use familiar operators with your custom objects, making the code more readable
and easier to understand.
Maintainability: Code that uses overloaded operators is often more concise and easier to maintain.
Flexibility: You can customize how operators work with your specific data type, allowing for more
expressive and powerful code.
How Operator Overloading Works:
To overload an operator, you define a special member function within your class that takes appropriate
arguments and has a return type.
The operator keyword (e.g., +, -, *) is used within the function name to indicate which operator is being
overloaded.
The compiler determines which overloaded operator function to call based on the operands and the
operator used in the expression.
Example: Overloading the + Operator for Complex Numbers:#include <iostream>
class Complex {private:
double real, imag;
public:
Complex(double r = 0.0, double i = 0.0) : real(r), imag(i) {}
// Overload the + operator for adding complex numbers
Complex operator+(const Complex& other) const {
return Complex(real + other.real, imag + other.imag);
}
// Other member functions for Complex class (e.g., -, *, /) can be overloaded similarly
friend std::ostream& operator<<(std::ostream& os, const Complex& c) {
os << c.real << " + " << c.imag << "i";
return os;
}
};
int main() {
Complex c1(2.0, 3.0);
Complex c2(4.5, -1.2);
Complex c3 = c1 + c2; // Calls the overloaded + operator
std::cout << "c1 = " << c1 << std::endl;
std::cout << "c2 = " << c2 << std::endl;
std::cout << "c3 = c1 + c2 = " << c3 << std::endl;
return 0;
}
(b) What are the advantages of operator overloading? [6]
Ans:- Operator overloading in C++ offers several advantages that enhance code readability, maintainability, and
expressiveness:
1. Natural Syntax:
One of the key benefits is the ability to use familiar operators with user-defined types (classes, structures).
This makes your code more intuitive and easier to understand. Instead of writing complex function calls to
perform operations on custom objects, you can leverage existing operators like +, -, *, /, ==, and others.
5/11
Consider a Complex class representing complex numbers. Without overloading, adding two complex
numbers might look like:
C++
Complex add(const Complex& c1, const Complex& c2);
With overloading the + operator, you can write:
C++
Complex c3 = c1 + c2;
2. Improved Readability:
Overloaded operators make code more concise and easier to follow. Instead of using verbose function
calls, you can express operations in a more compact and familiar way. This improves code readability for
yourself and others working with your codebase.
3. Maintainability:
Code that utilizes overloaded operators is often easier to maintain. The logic for operations like addition,
subtraction, or comparison is encapsulated within the overloaded operator functions, promoting
modularity and reusability. Changes to these operators can be localized, reducing the risk of unintended
side effects in other parts of the code.
4. Expressiveness:
Operator overloading allows you to create custom behavior for operators when working with specific data
types. This enables you to create more expressive code that aligns with the semantics of your custom
objects. For example, overloading the << (insertion) operator allows you to define how complex numbers
or other custom objects are printed using std::cout.
5. Consistency with Built-in Types:
By overloading operators, you can achieve a level of consistency between user-defined types and built-in
types. This makes your code more intuitive to work with, as the same operators behave similarly for both
types.
9. (a) Discuss with examples, the implications of deriving a class from an existing [9]
class by the ‘public’ and ‘protected’ access specifiers
Ans:- In C++,
how you derive a class from an existing class using access specifiers (public and protected)
determines the accessibility of the base class members in the derived class and subsequently, how objects
of the derived class can interact with those members. Here's a breakdown of the implications for public
and protected inheritance:
Public Inheritance:
Member Accessibility:
oPublic members of the base class become public members of the derived class.
oProtected members of the base class become protected members of the derived class (not directly
accessible outside the derived class or its friend classes).
oPrivate members of the base class are not accessible in the derived class or outside.
Object Usage:
oObjects of the derived class can access the public members of the base class directly using the dot
operator (.).
oProtected members of the base class can be accessed by member functions of the derived class, but not
directly from objects of the derived class.
Example:
class Shape {public:
virtual void draw() { // Can be overridden in derived classes
std::cout << "Drawing a shape" << std::endl;
}
};
class Circle : public Shape {public:
void draw() override { // Override draw() for circles
std::cout << "Drawing a circle" << std::endl;
}
int radius; // Public member specific to Circle
};
int main() {
Circle c;
c.radius = 5;
c.draw(); // Calls Circle's overridden draw()
return 0;
6/11
}
Protected Inheritance:
Member Accessibility:
oPublic and protected members of the base class become protected members of the derived class.
oPrivate members of the base class are not accessible in the derived class or outside.
Object Usage:
oObjects of the derived class cannot directly access any members of the base class (neither public nor
protected).
oMember functions of the derived class can access protected members of the base class.
Example:
class Animal {protected:
std::string name;
public:
Animal(const std::string& n) : name(n) {}
void makeSound() {
std::cout << "Generic animal sound" << std::endl;
}
};
class Dog : protected Animal {public:
Dog(const std::string& n) : Animal(n) {} // Call base class constructor
void bark() {
std::cout << name << " barks!" << std::endl;
// Can access protected member 'name' from Animal
}
};
int main() {
Dog d("Fido");
// d.name; // Error: name is protected in Dog
d.bark(); // Calls Dog's bark() which uses name
return 0;
}
(b) How does inheritance enable code reusability, explain with an example? [6]
Ans:- Inheritancein C++ is a fundamental concept that promotes code reusability by allowing you to create new
classes (derived classes) that inherit properties and behaviors from existing classes (base classes). This
eliminates the need to rewrite common code and helps you build more efficient and maintainable
programs.
Here's how inheritance enables code reusability:
Reduced Code Duplication: When you have multiple classes that share similar functionalities, inheritance
allows you to define those functionalities once in a base class. Derived classes can then inherit these
functionalities without the need to rewrite the code. This reduces redundancy and saves development
time.
Example:
Consider a scenario where you want to create classes for different types of shapes (e.g., Circle, Square).
These shapes might share some common properties like area and perimeter calculations.

class Shape {public:


virtual double getArea() const = 0; // Pure virtual function (explained later)
virtual double getPerimeter() const = 0; // Pure virtual function
};
class Circle : public Shape {private:
double radius;
public:
Circle(double r) : radius(r) {}
double getArea() const override {
return 3.14159 * radius * radius;
}
double getPerimeter() const override {
return 2 * 3.14159 * radius;
}
7/11
};
class Square : public Shape {private:
double sideLength;
public:
Square(double s) : sideLength(s) {}
double getArea() const override {
return sideLength * sideLength;
}
double getPerimeter() const override {
return 4 * sideLength;
}
};
10. (a) Explain Calling a Virtual Function Through a Base Class Reference. [7]
Ans:- In C++,
when you call a virtual function through a base class reference (or pointer), a concept called
runtime polymorphism comes into play. This allows the call to be resolved at runtime based on the actual
type of the object being referred to, even though the reference or pointer has the base class type.
Here's a breakdown of how it works:
Virtual Function: The function you want to call must be declared as virtual in the base class. This tells the
compiler to create a virtual table (vtbl) for the class and its derived classes. The vtbl stores pointers to the
actual implementations of virtual functions for each class in the inheritance hierarchy.
Base Class Reference: You declare a reference variable of the base class type and assign it the address of
a derived class object. This reference can only access members (variables and functions) that are public or
protected in the base class.
Runtime Resolution: When you call the virtual function through the base class reference, the compiler
doesn't know the exact type of the object at compile time. However, the base class reference still holds
the memory address of the derived class object.
Virtual Table Lookup: At runtime, the system uses the vtbl associated with the object's actual type to
locate the correct implementation of the virtual function being called. It then executes that specific
implementation.
Example:
class Animal {public:
virtual void speak() {
std::cout << "Generic animal sound" << std::endl;
}
};
class Dog : public Animal {public:
void speak() override { // Override speak() for dogs
std::cout << "Woof!" << std::endl;
}
};
class Cat : public Animal {public:
void speak() override { // Override speak() for cats
std::cout << "Meow!" << std::endl;
}
};
int main() {
Animal* animalRef; // Base class reference
Dog d;
animalRef = &d; // Assign address of a Dog object
animalRef->speak(); // Calls Dog::speak() at runtime (runtime polymorphism)
Cat c;
animalRef = &c; // Assign address of a Cat object
animalRef->speak(); // Calls Cat::speak() at runtime (runtime polymorphism)
return 0;
}
(b) What are benefits of calling virtual functions through base class? [3]
Ans:- Polymorphism:Enables code that works with various derived class objects through the base class
interface, promoting flexibility and code reusability.
8/11
· Loose Coupling: Base class references don't need to know the specific derived class type, making the
code more maintainable and adaptable to future changes.
(c) Write the difference between Early and Late Binding. [5]
Ans:-

11. (a) Explain Stream classes hierarchy with example [ 10 ]


Ans:- In C++, a stream refers to a sequence of characters that are transferred between the program and

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;
}

*** END OF PAPER ***

11/11

You might also like