Beruflich Dokumente
Kultur Dokumente
And
Explain the key features of OOP. Ans:
Procedural programming creates a step by step program that guides the application through a sequence of instructions. Each instruction is executed in order. Procedural programming also focuses on the idea that all algorithms are executed with functions and data that the programmer has access to and is able to change.
Object-oriented programming (OOP) is a programming paradigm using "objects" data structures consisting of data fields and methods together with their interactions to design applications and computer programs. Programming techniques may include features such as data abstraction,
Objects The instances of a class which are used in real functionality its variables and operations. Class Basic building blocks OOP and a single entity which has data and operations on data together. Inheritance- This is the process by which a class can be derived from a base class with all features of base class and some of its own. This increases code reusability.
Destructor is used to de-allocate m/m which is created by constructor It is similar to constructor by precesiding ~ sign. It cannot be overloaded, means in one program we can write only one destructor.
// example on constructors and destructors #include <iostream> using namespace std; class CRectangle { int *width, *height; public: CRectangle (int,int); ~CRectangle (); int area () { return (*width * *height); } }; CRectangle::CRectangle (int a, int b) { width = new int; height = new int; *width = a; *height = b; } CRectangle::~CRectangle () { delete width; delete height; } int main () { CRectangle rect (3,4), rectb (5,6); cout << "rect area: " << rect.area() << endl; cout << "rectb area: " << rectb.area() << endl; return 0; } Output: rect area: 12 rectb area: 30
. Set 1. Q 4. What do you mean by operator overloading? Illustrate with suitable example
for overloading Unary operators.
Ans: Operator overloading is an interesting feature of C++ that allows programmers to specify how various arithmetic, relational and many other operators work with user defined datatypes or classes. It provides a flexible way to work with classes and can make program code look obvious. Several operators such as dot operator, scope resolution (::) operator, conditional operator (?:) etc cannot be overloaded. Example: Unary operators act on only one operand. Some commonly used unary operators are unary minus (-), increment (++) and decrement (--) operators. //****This program illustrates the overloading of unary munus ( - ) operator****** #include class Minus { private: int a, b, c ; public: Minus( ) // Default Constructor { } Minus(int A, int B, int C) { a=A; b=B; c=C; } void display(void); //********Declaration of the operator function********** void operator - ( ); }; // End of the Class Definition //***********Member Function Definitions************* inline void Minus :: display(void) { cout << "\t a = " << a << endl ; cout << "\t b = " << b << endl ; cout << "\t c = " << c << endl ; } //*********Definition of the operator function*********** inline void Minus :: operator - ( ) { a = -a ; b = -b ; c = -c ; } //*************Main Function Definition*************** void main(void) { Minus M(5, 10, -15) ; cout << "\n Before activating the operator - ( )\n" ; M.display( ) ; -M ; cout << "\n After activating the operator - ( )\n" ;
..
Set 1. Q 5. Write C++ program which demonstrate the difference between static and
dynamic binding. Ans:
The following example demonstrates the differences between static and dynamic binding. The first example demonstrates static binding: #include<iostream> Using namespace std; Struct A { Void f() { cout<<Class A<<endl; } }; Struct B: A { Voidf() {cout<<Class B<<endl; } }; Void g(A& arg) { Arg.f(); } Int main () { B x; g(x); }
Ans:
We cannot have static and non-static member functions with the same names and the same number and type of arguments. Like static data members, we may access a static member function f() of a class A without using an object of class A. A static member function does not have a this pointer. Example: // static_member_functions.cpp #include <stdio.h> class StaticTest { private: static int x; public: static int count() { return x; } }; int StaticTest::x = 9; int main() { printf_s("%d\n", StaticTest::count()); } Output: 9 Nonstatic member functions have an implied argument, this, that points to the object through which the function is invoked. The type of this is type * const. These functions are considered to have class scope and can use class data and other member functions in the same class scope directly. Example:
#include <iostream> using namespace std; struct X { private: int a; public: void Set_a(int a) { // The 'this' pointer is used to retrieve 'xobj.a' // hidden by the automatic variable 'a' this->a = a; } void Print_a() { cout << "a = " << a << endl; } }; int main() { X xobj; int a = 5; xobj.Set_a(a);
..
In some cases it is possible to override the template-generated code by providing special definitions for specific types. This is called template specialization.
//base template class template<typename T1, typename T2> class X { }; //partial specialization template<typename T1> class X<T1, int> { }; int main() { // generates an instantiation from the base template X<char, char> xcc ; //generates an instantiation from the partial specialization X<char, int> xii ; return 0 ; } A partial specialization matches a given actual template argument list if the template arguments of the partial specialization can be deduced from the actual template argument list. . .
};
class Employee { private: std::string m_strEmployer; double m_dWage; public: Employee(std::string strEmployer, double dWage) : m_strEmployer(strEmployer), m_dWage(dWage) { } std::string GetEmployer() { return m_strEmployer; } double GetWage() { return m_dWage; } }; // Teacher publicly inherits Person and Employee class Teacher: public Person, public Employee { private: int m_nTeachesGrade; public: Teacher(std::string strName, int nAge, bool bIsMale, std::string strEmployer, double dWage, int nTeachesGrade) : Person(strName, nAge, bIsMale), Employee(strEmployer, dWage), m_nTeachesGrade(nTeachesGrade) { } };
Set 2. Q 2. Discuss the types of Inheritance with suitable example for each.
Ans:
Types of Inheritance: There are five different inheritances supported in C++: (1) Simple / Single (2) Multilevel (3) Hierarchical (4) Multiple (5) Hybrid
1) PROGRAM: PAYROLL SYSTEM USING SINGLE INHERITANCE: #include<iostream.h> #include<conio.h> class emp { public: int eno; char name[20],des[20]; void get() { cout<<"Enter the employee number:"; cin>>eno; cout<<"Enter the employee name:"; cin>>name; cout<<"Enter the designation:"; cin>>des;
E.No E.name des BP HRA DA PF NP 150 ram Manager 5000 1000 500 300 6200 2) Example of Multilevel Inheritance:
#include< iostream.h> #include< conio.h> class student // Base Class { protected: int rollno; char *name; public: void getdata(int b,char *n) { rollno = b; name = n; } void putdata(void) { cout< < " The Name Of Student \t: "< < name< < endl; cout< < " The Roll No. Is \t: "< < rollno< < endl; } }; class test:public student // Derieved Class 1 { protected: float m1,m2; public: void gettest(float b,float c) { m1 = b; m2 = c; } void puttest(void) { cout< < " Marks In CP Is \t: "< < m1< < endl; cout< < " Marks In Drawing Is \t: "< < m2< < endl; } }; class result:public test // Derieved Class 2 { protected: float total; public: void displayresult(void)
3) Example of Hierarchical Inheritance: #include <iostream.h> class Side { protected: int l; public: void set_values (int x) { l=x;} };
#include <string> class Person { private: std::string m_strName; int m_nAge; bool m_bIsMale;
public: Person(std::string strName, int nAge, bool bIsMale) : m_strName(strName), m_nAge(nAge), m_bIsMale(bIsMale) { } std::string GetName() { return m_strName; } int GetAge() { return m_nAge; } bool IsMale() { return m_bIsMale; } }; class Employee { private: std::string m_strEmployer;
.. Set 2. Q 3. Write a c++ program to implements the relational operator overloading for the distance class.
Ans: The following program implements the program for < relational operator overloading for the distance class. # include<iostream.h> class distance { private: int feet, inches; public: distance() {feet=0; inches=0;} distance(int f) {feet=f; inches=0;} distance(int f, int i) {feet=f;inches=i;} void display(); void getdata(); int operator < (distance d1) { if (feet<d1.feet) return 1; else if (feet==d1.feet) && (inches<d1.inches) return 1; else return 0; } }; void distance :: display() {cout<<feet <<" "<<inches<<endl;} void distance :: getdata() { cout<<Enter distance in feet and inches; cin>>feet >>inches;} void main() { distance d1,d2; d1.getdata(); d2.getdata(); if (d1<d2) cout<<d1.display() << is smaller; else cout<<d2.display()<< is smaller; } In the above program the d1 object invokes the operator < and d2 is passed as an argument. The return value is either 0 or 1 which indicates false or true respectively. Certain compilers support boolean datatype which can be alternatively used instead of integer. The above program also implements display and getdata member functions differently. The member functions are declared inside the class but are defined outside the class. But to specify that the member function belongs to the distance class, the class name is included along with the function name separated by the scope resolution operator (::). ..
Set 2. Q 4. Write the advantages of using exception handling with its basic models.
Ans: Advantage 1: Separating Error-Handling Code from "Regular" Code Exceptions provide the means to separate the details of what to do when something out of the ordinary happens from the main logic of a program. In traditional programming, error detection, reporting, and handling often lead to confusing spaghetti code. For example, consider the pseudocode method here that reads an entire file into memory. readFile { open the file; determine its size; allocate that much memory; read the file into memory; close the file; } At first glance, this function seems simple enough, but it ignores all the following potential errors. 1. What happens if the file can't be opened? 2. What happens if the length of the file can't be determined? 3. What happens if enough memory can't be allocated? 4. What happens if the read fails? 5. What happens if the file can't be closed? To handle such cases, the readFile function must have more code to do error detection, reporting, and handling. Here is an example of what the function might look like. errorCodeType readFile { initialize errorCode = 0; open the file; if (theFileIsOpen) { determine the length of the file; if (gotTheFileLength) { allocate that much memory; if (gotEnoughMemory) { read the file into memory; if (readFailed) { errorCode = -1; } } else { errorCode = -2; } } else { errorCode = -3; } close the file; if (theFileDidntClose && errorCode == 0) { errorCode = -4; } else { errorCode = errorCode and -4; }
list<Type> To choose a container, decide what sort of operations you will most frequently perform on your data, then use the following table to help you. Operation Access 1st Element Access Last Element Access Random Element Add/Delete at Beginning Add/Delete at End Add/Delete at Random Vector Constant Constant Constant Linear Constant Linear Deque Constant Constant Constant Constant Constant Linear List Constant Constant Linear Constant Constant Constant
vector<Type> deque<Type>
Time overhead of operation on secuence containers Each container has attributes suited to particular applications. The subsections and code samples below should further clarify when and how to use each type of sequence container. Vector #include <vector> The vector class is similar to an array, and allows array-type syntax, e.g. my_vector[2] . A vector is able to access elements at any position (referred to as "random" access in the preceding table) with a constant time overhead, O(1). Insertion or deletion at the end of a vector is "cheap". As with the string, no bounds checking is performed when you use operator []. Insertions and deletions anywhere other than at the end of the vector incur overhead O(N), N being the number of elements in the vector, because all the following entries have to be shuffled along to make room for the new entries, the storage being contiguous. Memory overhead of a vector is very low and comparable to a normal array. Deque #include <deque> The double-ended queue, deque (pronounced "deck") has similar properties to a vector, but as the name suggests you can efficiently insert or delete elements at either end. A deque, like a vector, is not very good at inserting or deleting elements at random positions, but it does allow random access to elements using the arraylike[] syntax, though not as efficiently as a vector or array. Like the vector an erase() or insert() in the middle can invalidate all existing iterators. List #include <list>
Lists don't provide [] random access like an array or vector, but are suited to applications where you want to add or remove elements to or from the middle. They are implemented as double linked list structures in order to support bidirectional iterators, and are the most memory-hungry standard container, vector being the least so. In compensation, lists allow low-cost growth at either end or in the middle. ..
Set 2. Q 7. Discuss how object diagrams are different from class diagram.
Ans: Object Diagram: Object diagrams are derived from class diagrams so object diagrams are dependent upon class diagrams. Object diagrams represent an instance of a class diagram. The basic concepts are similar for class diagrams and object diagrams. Object diagrams also represent the static view of a system but this static view is a snapshot of the system at a particular moment. Object diagrams are used to render a set of objects and their relationships as an instance. Purpose: The purpose of a diagram should be understood clearly to implement it practically. The purposes of object diagrams are similar to class diagrams. The difference is that a class diagram represents an abstract model consisting of classes and their relationships. But an object diagram represents an instance at a particular moment which is concrete in nature. It means the object diagram is more close to the actual system behaviour. The purpose is to capture the static view of a system at a particular moment. So the purpose of the object diagram can be summarized as: Forward and reverse engineering. Object relationships of a system Static view of an interaction. Understand object behaviour and their relationship from practical perspective
Class Diagram:
The class diagram is a static diagram. It represents the static view of an application. Class diagram is not only used for visualizing, describing and documenting different aspects of a system but also for constructing executable code of the software application. The class diagram describes the attributes and operations of a class and also the constraints imposed on the system. The class diagrams are widely used in the modelling of object oriented systems because they are the only UML diagrams which can be mapped directly with object oriented languages. The class diagram shows a collection of classes, interfaces, associations, collaborations and constraints. It is also known as a structural diagram.
..