0% found this document useful (0 votes)
72 views7 pages

BCS-031 Assignment

bcs 31 assignment

Uploaded by

Hemraj Chhonkar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
72 views7 pages

BCS-031 Assignment

bcs 31 assignment

Uploaded by

Hemraj Chhonkar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 7
OONIA; UBLICATION®. Ey sume Poona Course Code: BCS-031 Course Title : Programming in C++ ‘Assignment Number : BCA(3)031/Assignment/2023-24 Maximum Marks : 100 ‘Weightage : 25% www.ignousite.com fe ey Last Date of Submission : 31st October, 2023 (for July 2023, eas my +30th April, 2024 (for January 2024 session} ‘Note: This asignment only for students, not for el or re-uploadanyimedle or website, Alright rezerve to TGNOU Stody Helper. Iie lagal to share or reupload if anything like this found, then appropiate ction wil be taken and apaly copyright ACT 16 you. You wil be responsible for ilegal work. 50 don't share and upload on any medi Q1. Whatis a Virtual Base Class? How does it differ from a Base Class. Explain with examples. ‘Ans. Virtual Base Class: Virtual base classes in C++ are used to prevent multiple instances ofa given class from appearing in an inheritance hierarchy when using multiple inheritances. Base classes are the classes from which other classes are derived. The derived(child) classes have access to the variables and ‘methods/functions of a base(parent) class. The entire structure is known as the inheritance hierarchy. Virtual Classis defined by writing @ keyword “virtual” jn the derived classes, allowing only one copy of data to be copied to Class Band Class € (reterring to the above example]. It prevents multiple instances of a class appearing as a parent classin the inheritance hierarchy when multiple inheritances are used. Need for Virtual Base Class: To prevent the error and let the compiler work efficiently, we've to use a virtual base class when multiple inheritances occur. It saves space and avoids ambiguity: When a class is specified as a virtual base class, it prevents duplication of its data members. Only one copy of its data members is shared by all the base classes that use the virtual base class Ifa virtual base class is not used, all the derived classes will get duplicated data members. in this case, the compiler cannot decide which one to execute. Base Class: In an object-oriented programming language, a base class is an existing class from which the other classes are determined and properties are inherited. Its also known as a superclass or parent class. in general, the class which acquires the base class canhold all its members and some further data as well. ‘© Abase’class isan existing class from which the other classes are derived and inherit the methods and properties. ‘© Base class can't acquire the methods and properties of the derived class. ‘© The base class is also‘called superclass or parent class, Syntax: Class base_classname{.. } Example; Example without a virtual base class in C++ and see what the output looks like! fincude parity Using namespace sta; 4 ae S of class A{ public: AN cout << "Constructor A\n"; } ignou Study Helper-Sunil Poonia OONIAZ sey Tone Srv Hexpee UBLICATIONS. eS Sunt Poona ‘void display() { cout << "Hello form Class A \n"; ) class 8: public A { i class €: public A ( k class D: public B, public C { h int eint object.display(); } i output fay coer coor Soe) one aC Le eae) Pere) mec! In the above example, we create a Class Aand then two of Its derived classes, Class B and Class C. Class A has amethod that prints out a statement, Allthe derived classes must have inherited data members from Class A Next, we declare Class D, which inherits class B and class C. Since Classes B and C are child classes of A/and then D is the child class of B and C, Class D inherits data members of Class A from both B and C. Hence, duplication occiirs, and the compiler doesn’t know what to execute and throws an error. Output After removing line object display() Constructor A Constructor A Explanation: If we remove the line object.display() in main, the program will compile successfully, and the above output will be printed. it means two objects of class A were created, one from B and the other from C. That's why the call is ambiguous. But this situation is avoided if the virtual base class is used. Ignou Study Helper-Sunil Poonia Page 2 OONIA: 51 Tomo Styy HELPER Poonss e SuML POONA Syntax: If Class A is considered as the base class and Class 8 and Class C are considered as the derived classes of A. Note: The word “virtual” can be written before or after the word “public”. class B: virtual public A { // statement. i class C: public virtual A { // statement 2 ‘eh Let us see an example: “mat Using namespace std class A{ public: Al) // Constructor { cout << “Constructor A\n"; h class B: public virtual A { k class C: public virtual A { a class D: public B, public C{ hk int main() { D object; // Object creation of class D. return 0; ) Output: many In this case, we are using a virtual base class in C+, so only ane copy of data from Class A was inherited to Class D; hence, the compiler will be able to print the output. When we mention the base class as virtual, we avoid the situation of duplication and let the derived classes get only one copy of the data. Ignou Study Helper-Sunil Poonia Page 3 OONIA, 16 Tonov Stvoy Here UBLICATION®. / Sumi Poowia ‘There area few details that one needs to remember. Virtual base classes are always created before non-virtual base classes. This ensures all bases are created before their derived classes. 2. Note that classes B and C still have calls to class A, but they are simply ignored when creating an object of class D. If we are creating an object of class B or C, then the constructor of A willbe called. 3. Ifa class inherits one or more classes with virtual parents, the most derived class is responsible for constructing the Virtual base class. Here, class D is responsible for creating class A object. ‘Q2. What is a Template? What are its applications? Give an example. ‘Ans. Template: In programming, a template is@ powerful feature that allows the creation of generic classes or functions. ‘Templates enable the definition of code that can work with different data types, allowing for code reusability and flexibility. ‘Templates are primarily used in C++ but are also available in some other programming languages like D: Templates can be represented in two ways: fi et ‘© Function templates Class templates EY Function Templates: We can define a template fora function. For example, if we have an add() function, we can create versions of the add function for adding the int, float or double type values, Class Template: We can define a template fora class. For example, a class template can be created for the array class that can accept the array of various types such as int array, float array or double array, ‘Applications of Templates: 1. Generic Data Structures: Templates are commonly used to create generic data structures such as linked lists, arrays, ‘queues, and stacks that can work with any data type. This allows developers to create container classes that can hold Various types of elements without duplicating code for each data type. 2, Algorithms and Functions: Templates are utilized to define generic algorithms and functions that can operate on different data types. For example, you can create a generic sorting algorithm that ean sort an array of integers, floating- point numbers, or strings. 3. Smart Pointers: Smart pointers, lke std::shared_ptr and std::unique_ptr, use templates to manage memory automatically for different data types. 4. Containers in Standard Template Library (STL): The STLin C+ heavily utilizes templates to provide generie container Classes like std::vector, ste::map, std:set, ete. 5. Polymorphism and Function Overloading: Templates contribute to compile-time polymorphism, enabling function overloading for multiple data types. Example of a Template: Let's consider an example of a simple generic function that finds the maximum element in an array: Hinclude // Template function to find the maximum element in an array ‘template TfindMax(T arf] size) { irr 0]; i size; +4) { y: Zouov Stvoy HeLree Poon Ag e SUNIL POONA JBLICATIONS if (arrfi] > max) { max arrlil; } return max; int main() { int intArr{] = (10, 25, 5, 45, 30}; double doubleArr[] = {3.14, 2.71, 1.618, 0.707}; Int intMax = findMax(intArr, 5); double doubleMax = findMax{doubleArr, 4); std::cout << "Manimum integer: " << intMax << std:iend); std::cout <<"Maximum double: " << doubleMax << std::en return 0; } In this example, we define a generic findMax function using a template. It can work with any data type for which the comparison operator >is defined. We demonstrate its usage with both integer and double arrays. When the program is executed, it will find the maximum value in each array and print the fesults The output will be: ere jouble: 3.14 ‘As you can see, the same function findMax is used for both integer and double arrays, thanks to the template. This exemplifies the flexibility and reusability of templates in C++. Q3. What is iostream ? Write a short note onit. ‘Ans. iostream: iostream isa standard C++ header file that provides the basic input and output functionality in C++ programming, It stands for “input-output stream” and forms an essential part of the C++ Standard Library. iostream allows programmers to Interact with the console (standard input and output streams) and external files (fle streams) through a unified interface, making it easy to read input and write output from/to different sources. ‘The iostream library includes three main classes: iostream, istream, and ostream. These classes are responsible for handling input and output operations in C++ and offer Various member functions to perform tasks like reading, writing, formatting, and manipulating data. Here's a short note on iostream and its key aspects: 1. Standard Streams: The iostream library introduces three predefined stream objects for common input and output operations: ‘cin: The standard input stream. It is used to read data from the user via the console. © cout: The standard output stream. itis used to display output to the console. cerr: The standard error stream. Its used to display error messages or diagnostic information to the console. Ignou Study Helper-Sunil Poon Page OONIA; i Toney ‘Stuny HELPER UBLICATION® é Sum. Poowa Formatted Input and Output: The iostream library provides formatting capabilities for displaying output in a structured and organized manner. Programmers can use stream manipulators (e.g. setw, setprecision, setfil] to control the appearance of data being displayed. 3. Input and Output Operators: The istream and ostream classes define input (>>) and output (<<) stream operators, respectively. These operators enable straightforward data extraction from input streams and insertion of data into output streams, 4, Stream States and Error Handling: iostream provides member functions like fail), eof), and good) to check the state of the stream and handle errors appropriately. Whe) a stream operation fails, the stream enters a failed state, and further operations are disabled until the error is cleared. 5. File Handling with fstream: In addition to handling console 1/0, iostream also facilitates file /0 through the fstream Class, The fstream class inherits from istream and ostream, making it possible to read from and write to files using the same stream operators (>> and <<) used for console /0. 6. Custom Stream Buffers: Developers can create custom stream buffers by inheriting from streambuf class. This enables custom handling of input and output data, allowing programmers to redirect streams to diferent devices or implement specialized data processing. 7. Internationalization: iostream supports internationalization ((18n) through the use of locale-speeific facets, Programmers can use facets to control the formatting and parsing of numeric, date, and monetary valties based on different cultural conventions, 8, Stream Manipulation: The header provides additional manipulators for controlling the format of data displayed, ike setting the width of fields, specifying the precision of floating-point numbers, and aligning data in columns. Key components of iostream: 1. std::cin and std::cout: std:;cinis an object of the std::istream class used for reading input from the user, and std::cout is an object of the std::ostream class lised for writing output to the console. 2. Input (Extraction) Operator (>>): The input operator >> is ed to extract data from the input stream (st variables. 3. Output (Insertion) Operator (<«): The output operator << is used to insert data into the output stream (std::cout) for displayingon the console. in) into Example: include int main(){ int num; std::cout << "Enter a number: "; std::cout << "You entered: "<< num << std::endl; return 0; } In this example, we use std::cout to display the message "Enter a number: "on the console. The user can then input a number, and std::cin extracts that number into the variable num. Finally, we use std::cout again to display the message "You entered: " followed by the value of num, JOONIAZ ‘ot Touay Stvoy HeLPee UBLICATIONS. ‘Sh SuML POONA ees jostream is a fundamental component of C++ programming, simplifying input and output operations and making it easy to interact with the user and handle data from external sources like files. Its standardized interface and formatting capabilities allow for more readable and maintainable code. Programmers can use iostream to build robust and interactive applications with rich user experiences and wellstructured data presentation, Ignou Study Helper-Sunil Poonia Page?

You might also like