Download as pdf
Download as pdf
You are on page 1of 131
Page No #102. a ___ Object Oriented Programm: Chapter-1 i Principles of object oriented Programming (Questions) _ 1 What is object-oriented programming? CR Josie aon 2 What is Procedure ~ oriented progtamming? : ienguagea'e 3 . How does object-oriented programming different from procedure-oriented language (2020,2015;2010) 4. Basi izati function in an object-oriented programming. asic organization of data and function in an obj! (2016,2013,2010) 5. Describe the features of object -oriented programming. __(2018,2016,2014,2012,2010) 6. Difference between Structisred Programming and Object Oriented Programming. 7. Application of object-oriented programming technology in various area. 8) Describe the major part C+ of programming language. 9 . Difference Between Object Based and Object Oriented Languages.(2017,2013) 10. What is abstract data type(ADT) ?° Mad 11. Difference between data abstraction and data encapsulation? (2017,2014,201| 12. What is reusability ? How do you achieve this in C+ ? (2011) 13. Define system design? Explain briefly the steps involved in object-oriented design approach (2012 14, Different between Object and class. (2017) 15. Distinguish between Inheritance and polymorphism. 16.What do you mean by dynamic binding?How is it useful in OOP? (2017) 17.Explain the data types of C++.(2019) 18. Write a C++ program that inputs a string from the keyboard and determines the length of string. ite a si 4 (2014) 19. Write a simple C++ program to manipulate a stack where push and pop functi = h manipulation. push and pop functions are used to help thi 20, Write a C++ program to evaluate the following function (2014) Vy? ty? ty? ay? sum=1+(5) +(5) +(3) +() + 21. Define the following terms . (2020). i. Inheritance ii, Data Abstruction iii. Data Encapsulation ~ 22.“Encapsulation reduces the complexity”: justify your position. (2020,2014,2012) Object Oriented Programming _ Page No #103 Chapter-1 Principles of object oriented Programming | ¥ ‘ 1. What is object-oriented programming? (2020,2018,2015,2014, 2012, 2010) | Ans: * Fi Object-Oriented Programming fr "Object-Oriented Programming" refers toa programming methodology based on objects, instead of just functions and procedures, These objects are organized into classes, which allow individual objects to be group together. Most modem programming languages including Java, C++, PHP are object-oriented languages, and many older programming languages now have object-oriented versions. An "object" in an. OOP language refers to a specific’ type, or “instance,” of a class. Each object has a structure similar to other objects in the class, but can be assigned individual characteristics. An object can also call functions, or methods, specific to that object. an 2 .What is Procedure — oriented programming? (2016, 2015) ‘Ans: : Procedure — otiented programming : A program in a procedural language is a list of instruction where each statement tells the computer to do something. It focuses on procedure (function) & algorithm is needed to perform the derived computation. When program become larger, it is divided into * function & each function has clearly defined purpose. Dividing the program into functions & module is one of the cornerstones of structured programming. E.g.:- ¢, basic, FORTRAN. Page No #104 ject Onented Progamming, | 3. How does object-oriented programming different from procedure-oriented language ? Ans: (2020,201: 2010) Difference Between Object Oriented Programming (OOP) & Procedure Oriented Programming (POP, Procedure Oriented Divided Into ‘Object Oriented Programming In OOP, program is divided into parts Tn, POP, program is divided into, small Private, Protected, etc. called objects. parts cilled functions. [Importance Tin OOP, Importance is given (0 the data [In POP. Importance is nol given rather than procedures or functions because | todata but (0 functions aswell hen it works asa real world as sequence of actions to be done. | Approach (OOP follows Botiom Up approach. POP follows Top Down approsich. ‘Accessspecifier | OOP has access specifiers named Public, | POP does not have any access specifier DataMoving In OOP, objects can move and communicate with éach other through member functions. in POP, Data can~-move freely from function to function in the system: Expansion OOP provides an easy way to add new di and function To add new data and function in POP is nal so easy. : Tn OOP, data can not move easily from function to function, it can be kept public ‘or private so we can control the access of data In POP, Most function uses Global data for sharing that can be accessed freely from function to function in the system VB.NET, C#.NET. [DataFliding | OOP provides Data_Hiding so | POP does not have any proper way for provides more security hiding data so itis less secure. Examples Example of OOP are: C+, JAVA, | Example of POP are : C, FORTRAN, Pascal, (4. Basic organization of data and function in an object-oriented program Ans: Object- 8. (2016,13,10)_| ation programs by creating partitioned memory arca for both data and functions that can be used as templates for creating copics of such modules on demand. An object is considered to be a partitioned area of computer memory that stores data and set of operations that can access that data . Since the memory partitions are independent the objects can be used in a variety of different programs without modifications. Object 6 Object 1 1 Date iwoor Object Oriented Programming __ Page No # 105 [Describe the features of object -oriented programming. ‘Ans: ; ‘The features of object -oriented programming: (2018,2016,2014,2012,2010) Emphasis is on data rather than procedure. B Programs are divided into what are known as objects. @ Data structures arc designed such that they characterize the objects ®@ Functions” that operate on the data of an object arc tied together in the data structure Data is hidden and cannot be accessed by external functions New data and functions can be easily added whenever necessary. Follows bottom-up approach in program design. 6. Difference between Structured Programming and Object Oriented Programming. (2012) Difference between Structured Programming and Object Oriented Programming: [Structured Programming Object Oriented Programming (Stnctured Programming is designed which | focuses on process/ logical structure and then data required for that process. Object Oriented Programming is designed which focuses on data. ‘Siucured programming follows _ top-down Object oriented programming follows bottom-up | approach. approach. "Structured Programming is also known as Modular | Object Oriented Programming supporis Programming and a subset of procedural | inheritance, encapsulation, abstraction, programming language. polymorphism, etc. In Structured Programming, Programs are divided into small self contained functions. In Object Oriented Programming, Programs are divided into small entities called objects. | Secured Programming is less secure as there is no way of data hiding Object Oriented Programming is more secure as having data hiding feature. Structured Programming can solve moderately complex programs. Structured Programming provides less reusability, Tore function dependency. Object Oriented Programming can solve any complex programs: Object Oriented Programming provides more reusability, less function dependency Less abstraction and less flexibility. More abstraction and morc flexi _7 - Application of object-oriented programming technology in various area. (2015) des the followings % Real Time Systems Design 2 % Simulation and Modeling System interest in software engineers can be found in using OOP. ‘cations of OOP are gaining importance in many areas. The most important area is the user face design such as windows. It has also got importance in real business systems as they are complicated and use many methods and OOP can simplify those. ‘The promising arcas Page No #100. nen an __-Object Oriented Programm, Object Oriented Database Object Oriented Distributed Database Client-Sarver System Hypertext, Hypermedia : ‘Neural Networking and Parallel Programming, Decision Support and Office Automation Systems. CIM/CAD/CAM Systems . " Al and Expert Systems ; > ['8) Describe the major part C++ of programming language. (2015) ‘Ans: Major part C++ of programming language: The Parts of a C++ Program finclude using namespace a} int main( eainming of function nameduais a beginningotBlaextor wasn there!" ; —outputstatement J Send 0 backto operating system ‘end of block for mais : cout << “Hello, return 0; yon “I sample C++ program, in C++ Lines beginning with two slash signs (//) are comm: by the programmer and have no effect on the behavior of the program. Programmers them to include short explanations or observations concerning the code or program this case, itis a brief introductory description of the program. #include Lines beginning with a hash sign (2) are directives read interpreted by what is known as the preprocessor. In this case, the directive #inc ‘, instructs the preprocessor to include a section of standard C++ code, kno as header iostream, that allows to perform standard input and Output operations. int main () This line initiates the declaration of a function. Essentially, a function group of code’ statements which are gi 'main" to the group of code statement begins with the main function regardl the code. std::cout, « "Hello World!"; This statement has three parts: First, std:scout, w! identifies the standard character output device (usually, this is the computer sere: Second, the insertion operator («), which indicates that what follows is inserted td.scout. Finally, a sentence within quotes ("Hello world!"), std::cout. y is the content inserted 1 the standard output. ‘Ans: Difference Between Object Based and Object Oriented Language: ‘Support of| features Object Based Language Object Based Language docs not support all the features of Oops Object Oriented Language ‘Object Oriented Language suppons all the features of Oops Inheritance Object Based Language Does Not Support Oops feature i.e. Inheritance. ‘Object Oriented Language supports all the Features of Oops including Inheritance Sample Visual Basic is an Object based Programming Language because you can use class and Object here but cannot inherit’ one class from another class i. it does not support Inheritance CH is an Object Oriented Languages because it supports all the concepts of Oops like Data _—_ Encapsulation, Polymorphism, Inheritance, Data ‘Abstraction , Dynamic Binding ete Example Javascript, VB are example of Object Based Language. CH, JAVA are example of Object Oriented Languages. [10. What is abstract data type (ADT) ?. Ans: ‘Abstract Data type (ADT) is a type (or class) for objects whos .¢ behavior is defined by a set of 1 value and a set of operations. The definition of ADT only mentions what operations are to be performed but not how these operations will be implemented. It does not specify how data will be orwanized in memory and what algorithms will be used for implementing the operations. It is called “abstract” because it gives an implementation independent view. The process of providing only the essentials and hiding the details is known as abstraction. Examples~* size(), isEmpty(), get() - i [A1. Difference between data abstraction and data‘encapsulation? (2017,2014,2011) Ans: Difference bétween data abstraction and data encapsulation: _ Data abstraction Data encapsulation Basic What elements are necessary to Hides the complexity of a system build a system E f _ Application During ‘design Tevel! During ‘Implementation level E Focus Focus is on "what" should be Focus is on "how" it should be done done Achieved ‘Achieved through encapsulation ‘Achieved through making the members of a class as ‘private’. Example The GUI of a mobile phone, it ‘After the icon is clicked, the end ‘ has some icons to click on, which | user has no idea regarding, its on click perform the specific implementation details, function 0 #108 Object Oriented Progamming (12. What is reus gout) | Ans: a . i ived classe Reusability: Reusability means the reuse of propertics of the base ‘class in the deriv 8. 5 ; tures in the Reusability permits the reuse of members ofthe previous class. We can add extra een cxisting class. This is possible by creating a new class from the existing class. have the features of both the old and the derived new class. (Inheritances), the base class is reused. ability 2 How do you achieve this in CH¥ ? Reusability is achieved using inheritance. Inheritance and reusability are not different from cach other. The'outcome of inheritance is reusability. The base class is also called super class, parent, ‘or ancestor, and the derived class is called subclass, child, or descendent. It is also possible to derive a class from a previously derived class. A class can be derived from more than one class. 13. Define system design? Explain briefly the steps involved in object-oriented design approach. . (2012) ‘Ans: System design: Object Oriented Design is the concept that forces programmers to plan out their code in order to have a better flowing program. The origins of object oricnted design is debated, but the first languages that supported it included Simula and Small Talk. The term did not become popular until Grady Booch wrote the first paper titled Object-Oriented Design, in 1982 Steps involved in object-oriented design approach: Object Oriented Design is defined as a programming language that has 5 conceptual tools to aid the programmer. These programs are often more readable than non-object oriented programs, and debugging becomes easier with locality. Language Concepts The 5 Basic Concepts of Object Oriented Design are the implementation level features that are built into the programming language. These features are often referred to by these common names: Encapsulation : A tight coupling or association of data structures with the methods or functions that act on the data. This is called a class, or object (an object is often the implementation of a class). " Data Prote The ability to protect sqme components of the object from external entitics. . This is realized by language keywords to enable a variable to be declared as private or protected to tlic owning class. Inheritance: The ability for a class to extend or override functionality of another class, The so called child class has a whole section that is the parent class and then it has it’s own set of functions and data e: A definition of functions or methods, and their signatures that are available for use to Interfac instance of an object. manipulate a given i mm; The ability to define different functions or classes as-having the same name but a his! Polymorp Mt data tyPcs- taking differen Object Oriented Programming _ Page No #109 (14. Different between Object and class (2017) ‘Ans: BASIS FOR ° COMPARISON OBJECT CLASS | Definition An instance of a class | A template or blueprint with which | is known as Object. | objects are created is known as Class. Type of entity Physical Logical | Creation Object is invoked by | Class is declared by using class keyword. new keyword. Memory allocation | Creation of object | The formation of a class doesn't allocate consumes memory. | memory guish between the Inheritance and polymorphism. * < BASIS FOR : : COMPARISON INHERITANCE POLYMORPHISM | Basic Inheritance is creating a new Polymorphism is basically a | class using the propertics of the | common interface for multiple | already existing class. forin. | | Implementation | Inheritance is basically Polymorphism is basically | implemented on classes. implemented on function/methods. Use To support the concept of Allows object to decide which reusability in OOP and reduces, | form of the function to be invoked the length of code. - when, at compile time (overloading) as well as nun time (overriding). Forms Inheritance may be a single Polymorphism may be a compile inheritance, multiple inheritance, | time polymorphism (overloading) multilevel inheritance, * or run-time polymorphism hicrarchical inheritance and (overriding). hybrid inheritance, Example “The class ‘table’ can inherit the | The class 'study_table’ can also. feature of the class ‘furniture’, as | have function ‘set_color()' and a a 'table' is a ‘furniture’. class ‘Dining_table' can also have function 'set_color()" so, which form of the set_color() function to invoke can be decided at both, compile time and run time, _Object Qaented I Tape No.#110__ oe [16.What doyou mean by dynamic binding? How ‘Ans: Dynamic Binding: je to be executed in response Binding refers to the linking of a procedure éall to the oe tien poe call. Dynamic binding/late-binding means that the cade associate’ ans ckesn Not known until the time of the call at runtime. It is associa inheritance. Dynamic binding in OOP: . Te 5 > To allow software systems to be more easily extended during both developmes inheritance. >Allow dynamtic polymorphism, >Obviates need for abstract classes(c.g., Fruit class, peel method) ; oh a >While other forms of dynamism in languages tend to be compromise efficiency in the system, dynamic binding involves little overhead. it useful in OOP. * [17 -Explain the data types of CHE Ans? A data type determines the type and the operations that can be performed on th C++ provides various data types and each data type is represented differently wi the computer's memory. The various data types provided by C++ are built-in ¢ types, derived data types and user-defined data types as shown in Figure. Qo19) Various Data Types in C++. Built-In Data Types The basic (Fundamental) data types provided by c++ are integral, floating point and void & type. Among these data types, the integral and floating-point data types can be preceded” several type modifiers. These modifiers (also known as type qualifiers) are the herwonts Object Oriented Programming Page Noe WI alter either size or range or both of the data types. The various modifiers are short, long. signed and unsigned. By default the modifier is signed In addition to these basic data types, ANSI C+ has introduced two more data types namely, bool and wehar t, < : Integral Data Type: The integral data type is used to store integers and includes char (character) ‘and int (integer) data types Char: Characters refer to the alphabet, numbers and othtr characters (such as {, @. #, ete.) defined in the ASCII character set. In C++, the char data type is also treated as an integer data type as the characters are internally stored as integers that range in value from -128 to 127, The char data type occupies } byte of memory (that is, it holds only one character at a time) ‘The modifiers that can precede char are signed and unsigned. The various character data types with thgir size and range ave listed in Table ‘Character Data Types 4 =128t0 127 Ceowaaer foot. ep eo mamet [ese Da ee all, Int: Numbers without the fractional part represent integer data: In C¥4, the int dain type is used to store integers such as 4, 42, 5233). numbers such as 4.28, -62.533- are listed in Table 232,°-745.-Thos, it) cannot store ‘The various integer data types with their size and range Page No # Object Oriented. to aa ‘age No # 412. S These) Saag ee Pt anise Dean is used to store mbers Floating-point Data ‘Type: A floating-point data type sree eat and double’ dats such as 3 .28, 64. 755765, 8.01, -24.53. This data type incl senge are listed in Table {ypes. The various floating -point data types with their size a Floating Point Data Types ision Void: The void data type is used for specifying an empty parameter list ° s pein tat type for a function. When void is used to specify an empty parameter ae function does not take any arguments and when it is used as a return type for a ssn i indicates that a function does not retum any value. For void, no memory is allocated and hence, i cannot store anything. As a result, void cannot be used to declare simple variables, however, it can be used to declare generic pointers. Derived Data Types: Data types that are derived from the built-in data types are known as derived data types. The various derived data types provided by C+ are arrays, junctions, references and pointers, Array An array is a set of elements of the same data type that are referred to by the same name. Alll the clements in an array are stored at contiguous (one after another) memory locations and cach clement is accessed by a unique index or subscript value. The subscript value indicates the Position of an clement in an array, Function A function is a self-contained Program segment that carries out a specific well-defined task. In C++, every program contains one or more functions which can be invoked from other parts of a program, if required. : Reference A reference is an altemative name for a variable. That is, a reference is an alias fora variable in a program. A variable and its reference can be used interchangeably ina program as both refer to the same memory location. Hence, changes made to i a any of the: ’, i ‘Feflected in the other (on a reference), Y offthem (say, a variable) are Pointer A pointer is a variable that can store the memory allow to use the memory dynamically. Tha is, with the het or de-allocated to the variables at Tun-time, thus, making a address of another Variable, Pointers P of pointers, memory can be allocated Program more efficient, Object Oriented Programming User-Defined Data Types Various user-defined data types provided by C++ ry are structures, unions, enumerations and classes. . Structure, Union and Class: Structure and union are the significant features of C | : Structure and union provide a way to group similar or dissimilar data types referred to aes name. However, C+ has extended the concept of structure and union by incorporating cman features in these data types to support object -oriented programming. CH offers a new user-defined data type known as class, which forms the basis of object-oriented programming. A class acts as a template which defines the data and functions that are included in an object of a class. Classes arc declared using the keyword tlass. Once a class has been declared, its object can be easily creatcd. Enumeration: An enumeration is a set of named integer constants that specify all the permissible values that can be assigned to enumeration variables. These set of permissible values are known as enumerators. For example, consider this statement. China}; // declaring an dH enum type (country is a tag name) , consisting of enum country {US, UN, In In this statement, an enumeration data-type country enumerators US, UN and so on, is declared. Note that these enumerators represent integer values, so any arithmetic operation can be performed on them. Countryl = 35 warning Country = UN; I Walid Country = (country) 3; //valid C++ also allows creating special type of enums known as anonymous enums, that is, cnums without using tag name as shown in this statement. UN<3, India, Chin enum {US, The enumerators of an anonymous enum can be used directly in the program as shown here. int count = US; Object Onented Prossarnng Keyboard and determines the lengy> ~ Super eni (0, Hinclude ‘ oe int main() { int i,count=0; char ch[20], cout<<"Enter any string: "; gets(ch); for(i=Ozch{i]'="\it+) { ‘count++; } ‘cout retum 0; 3 ‘tring Length: "< using namespace std; #define MAX 1000 class Stack t int top; * public: int a[MAX]; Maximum size of Stack Stack() { top = -1; ‘bool push(int x); int popQ): bool isEmpty(): ool Stack::push(int x) { if (top >= MAX) { cout << "Stack Overflow"; retum false; } else { al++top] =x; return true; int Stack::pop() { * if (op <0) { cout << "Stack Underflow"s retum 0; yu + else { int x = a[top—]; Object 1 ee bool Stack::isEmpty0 return (top < 0); i # 3 # . I) Driver program to test above functions is) int main() t struct Stack s; { ; s.push(10); < Pay spush(20); f s.push(30); cout << s.pop() <<” Popped from stackin"; return 0; 20. Write a C+ program to evuluate the following function:(2104) 2 2 2 2 an=1+() +6) +@) +G)* Ans: . #include #include int main( ){ float i,n,sum,k; Page No #117 for(i=0; I<= m; i++){- k= pow(1/ii); sum = sum +k ; } cout << “the sum of he series is : "<< sum; return 0: 3 | 21. Define the following terms (2020) i. Inheritance I Data Abstruction Data Encapsulation Answer: i. Inheritance The capability of a class to der called Inheritance. Inheritance | Programming. + Sub Class: The class tha or Derived Class. . « Super Class:The class whose Class or Super class. * Reusability: Inheritance supports the concept of “reusability”, ie. when we want to create a new class and there is alread cludes some of the code that we want, we can derive our new class from the i this, we are reusing the fields and methods of the existing class rive properties and characteristics from another class is 's one of the most important features of Object-Oriented t inherits properties from another class is called Sub class properties are inherited by sub class is called Base a class that in existing class. By doin: w can be Derived Class of Animal Base Class. Example: Dog, Cat, Cov "ANIMAL CLASS cat cow oe class c1ass Lass Obiect Oriented Program: Data Abstruction on is one of th ssential and important features of object-orier mm means displaying only essential information ction refers to providing only essential information abou: de world, hiding the background details or implementation iii, Data Encapsulation ation also leads to data abstraction or hiding. As using encapsulation al e data. In the above example, the data of any of the section like sales, finance 0 yunts are hidden from any other section. accor “Encapsulation reduces the complexity”- justify Answer: your position. (2020,2014.2012) Encapsulation is one of the fundamentals of OOP (object-oriented_programming). It refers to the bundling of data with the methods that operate onthat data Encapsulation is used to hide the values or state of a structured dataobject inside a class, preventing unauthorized parties’ direct access to them. Encapsulation helps in isolating implementation details from the behaviorexposed clients of a class (other classes/functions that are using this class), andgives you more control over coupling in your code. C Complexity mainly arises from a multitude of connections between various parts of the syste Encapsulation hides some parts of the system so they cannot be connected to reduces t complexity . Chapter:2 Tokens, Expressions and Control Structures Question 1._ Different types of operator used in C++ language and state their purpose. (2011) 2. Describe the memory management operator in C++. (2016,2012,2011) 3. Why array is called derived data type? (2016,2010) 4. What is the bool data type? (2016) 5, What is the dynamic initialization of a variable ? Give an example. (2015) 6. What are the advantage of new operator over malloc( ) function. (2015) 7. Dynamic memory allocation and de allocation operators new, new!] ,delete,deletel] - . (2014,2107) 8, What is dynamic memory allocation? (2020,2017,2009) 9, How can memory be allocated using ‘new’ and release it using “delete”? (2020,2017,2009) 10. Explain the use of Unary and Ternary operator. (2013) 11, Role of scope resolution operator in C+, Explain with example. (2018,2012) 12. How does the following statement differ?(2013,2011) 13. Char *const p; ii) Char const *p; 14, write a program to evaluate the following function to 0.0001% accuracy:. (2017,2014) SUM= 1+ (1/2)*2 + (1/3)*3 + -.(1/n)*n 15, write a program to evaluate the following function to 0.001% accuracy: Sinx= x - x43/3! + x5/5! = x0 7/74 16, write a program to evaluate the following function to 0.001% accuracy: Cosx= 1- x 2/2! + xA4/4! - x*6/61 + pter:2 Cha _-Qhject Oriented Programming [ iferent pes of operator used in. CH language and state their purpose .@0ii) Dil ae of operator used in_C#+ language :An operator is a symbol that tells the compiler 9 perform specific mathematical or logical manipulations. C-++ ig.rich in builtein operators ang provide the following types of operators — “Assignment Operators “Relational Operators Arithmetic Operators Logical Operators - Bitwise Operators Assignment Operators Operates '=' is used for assignment, it takes the right-hand side (called rvalue) and copy it into the left-hand side (called Ivalue), Assignment operator is the only operator which can be overloaded but-cannot be inherited, Relational Operators: Relational operators are used for comparison of the values of two operands. For example checking if one operand is equal to the other operand or not, an operand is greater than the other Operand or not etc. Some of the relational operators are (==, > <=). Arithmetic Operators . C++ uses operators to do arithmetic. It Provides operators for five basic arithmetic calculations addition, subtraction, multiplication, division, and taking the modulus. Each of these ‘operators uses two valucs (called operands) to calculate a final answer, Together, the operator and its operands constitute an expression Logical operators -Logical Operators are used to combine two or more conditions/constraints or to complement the evaluation of the original condition in consideration NOT-! AND - && . -OR-|| . The operator ! is the C++ operator for the Boolean operation NOT. It has only one operand, to it right, and inverts it, producing false if its operand is true, and true if its operand is false. . a le erators && and | arc used when evaluating two expressions to obtain a sing! The logical OFT Tne operator && corres . 7 jonal result Ponds to the Boolean logical operation AND, which relational Fes) th its operands are true, and false otherwving ; i yields true Bitwise operator works on bits and perform bit-by-bit operation. The truth tables for &, |, and are as follows Pp ‘a p&q pia pq 0 0 0 0 0 0 1 0. 1 1 1 1 1 4, 0 1 0 “0 1 i 2. Describe the memory management operator in C++. (2016,2012,2011) Ans: Memory management operator in C- There are two types of memory management operators in C++: new delete ‘These two memory management operators are used for allocating and freeing memory blocks in efficient and convenient ways. New operator: The new operator in C++ is used for dynamic storage allocation, This operator can be used to create object of any type. General syntax of new operator in C++: pointer variable = new datatype; Inthe above statement, new. is a keyword and the pointer variable is a variable of type dataype For example: int *a = new int; a= 20; Or int *a = new int(20); Inthe above example, the new operator allocates sufficient memory to hold the object of datatype int and returns a pointer to its starting point. the pointer variable a holds the address of memory space allocated. Delete operator: The delete operator in C++ is used for releasing memory e when the object is no longer needed, Once a nev operator is used, it is eMicient to use the corresponding delete operator for release of memory. General syntax of delete operator in C++: delete pointer variable; for example int *a = new int, "a= 20, cout« delete The output is a=" Object Oriented Programming, | ‘[B._What is dynamic memory allocation? (2020,2017,2009) ] Answer: Dynamic memory allocation in C/C++ refers to performing memory allocation manually -by programmer. Dynamically allocated memory is allocated on Heap and non-static and local variables get memory. allocated on Stack. C+ supports these functions and also has two operators new’ and delete that perform the task of allocating and freeing the. memory : How can memory be allocated using ‘new’ and release it using ‘delete’? (2020,2017,2009) ‘Answer: C++ supports these functions and also has two operators new and delete that perform the task of allocating and freeing the memory. Memory allocation operator new The new operator denotes a request for memory allocation on the Heap. If sufficient memory is available, new operator initializes the memory and returns the address of the newly allocated and initialized memory to the pointer variable. Syntax to use new operator: To allocate memory of any data type, the syntax is: pointer-variable = new data-types Here, pointer-variable is the pointer of type data-type. Data-type could be any built-in data type including array or any user defined data types including structure and class. Example: // Pointer initialized with NULL ~ // Then request memory for the variable int *p = NULL; p= new int; Memory deallocation operator delete delete-expt ressions to deallocate storage previously allocated for a single object. The behavior o! the standard library implementation of this function is undefined unless ptr is a null pointer or is pointer previously obtained from the standard ps library implementation — of operat new(size_t) or operator new(size_t, std::nothrow_1). Since it is programmer’s responsibility: to deallocate dynamically allocated memory programmers are provided delete operator by C++ language. Syntax: // Release memory pointed by pointer-variable delete pointer-variable; Here, pointer-variable is the pointer that points to the data object created by new. Page No #125 [10 Explain the use of Unary and Ternary operator (2013) | ‘Ans: 7 Unary operator : Ithas only one operand. There are two main unary operators “increment operator “decrement operator Increment Operator The increment operator(++), which is to increment the variables or the constants, Increment is of two types like pre-increment and post-increment operator. The pre-increment operator will assign the vale to the variable and then increment the value by one. The post-increment operator will increment and then assign that value to the variable. we will use increment operators mostly in the looping like for, while and do.....while. Decrement Operator 2 ‘The decrement operator(-), which is to decrement the values of variables or constants. Its similar like increment types. But here it’ll decrease the value instead increasing Ternary Operator Ternary operator is also known as conditional operator. It has three operands. Syntax; expr?stmt l:stmt2; Ifthe expression is true, then the statement! will be executed, Else statement2 will be executed. J LL. Role of scepe resolution operator in C++. Explain with example. (2018,2012) Ans: — Scope resolution operator: In C++ language the scopc resolution operator is written "::" C++ supports to the global variable from a function, Local variable is to define the same function name, ‘Identify variables with usc of scope resolution operator when we use the same name for local variable and global variable ( or in class or namespace ) + Resolution operator is placed between the front of the variable name then the global variable is affected.If no resolution operator is placed between the local, variable is affected. identifier // for Global Scope class-name ‘identifier // for Class Scope namespace identifier // for Namespace Scope Usimple syntax ‘global variable name “xample: “include using namespace std; Object Oriented Programmin, Rage.No # 126. char ¢ ='a': // global variable int main() { char ¢ ='b’; //local variable cout << "Local variable: "<< ¢ << "\n"; cout << "Global variable: " << ::¢ << "\n"; //using scope resolution operator return 0; } Global variable: a Scope resolution operator in clas #include using namespace std; class programming { Public: void output(); //function declaration Hs // function definition outside the class void programming::output() { cout << "Function defined outside the class.\n } ‘int main() { Programming x; X.output(); Teturn 0; 3 Output: Function defined outside the class [ 12. How does the following statement differ? © (2013,2011) i) Char *const py ii) Char const *p;~ : Ans i)Char_*const_p char * const p is a constant pointer to a variable(i.e, you can’t change the pointer) #include int main() { char z; char y; /* Invalid, gives compiler error "uninitialized const p" */ // char * const p;_,// Need to initialize at declaration time char * const p = &2;// Address cannot be changed, Must be initialize at declaration time *p='A ed Programming _ vier p invalid gives compiler error snment of read-only variable p" */ Page No #127 jjoonst pointer can't be change, must be initialize at declaration time print" \n".*p); mun 0} jyChar_const “p. [const char *p and char const % ‘p both are same/ dhar const *p points to constant character(You ¢ inted characters using that pointer). Finclude int main ( char 2= char Y; ‘an change where p points, but you can’t change const char *p = &y; _ // Can’t change pointed characters using pointer, can change pointer = hz: /* Invalid, gives compiler crror "assignment of read-only location *p” */ pin 0°) retumn 0; } 1/ You can’t change pointed characters using pointer [13. ‘write a program to evaluate the following function to 0.0001% accuracy:._(2017,2014) SUM= 1+ (1/2)*2 + (1/3)°3 + ‘Ans: #include #include #include Void main() { clrscr(); float i,n,sum,k; Cout<<"Enter the last numb: cin>>n; Sum=0; forli=lsi<= { kepow(1/i,i); punt, Cout<<"The sum of the series is:"< Hinelude #includesmath.h> int fact(int n) t iftfn==0) retum n*fact(n-1); } : void main() { clrser(); Jong int i; long float sinx=0,x=30; X=(3.1416/180)*x; sinx=sinx+(pow(-1,i+1)*pow(x,i)/facti); cout<<"sinx="< #include #include int fact(int n) Oe Page. No #128 14.write a program to evaluate the following function (o 0. Sinx= x - x43/31 + x45/5! - x9 7/7! Ans: #include #include #include int fact(int n) At if{n==0) return n*fact(n-1); oy | yoid main() { clrscr(); long int i; | | long float sit X=(3.1416/180)*x; i<=7;i4=2) sinx=sinx+(pow(-1,i+1)*pow(x,i))/fact(i); cout<<"sinx="< return type “ name-of the function “argument list like int sum(int nl, int n2); Here, «return type - int : name of the function - sum «argument list - (int nl, intn2) ae. i it ues and it is used as the return data type that it specifies an empty set of val ee ee function that does not return @ value is type for functions that do not return a value. Thus, @ declared as follows: void fanction_name(parameter list); Ifa function takes no argument, you should sp‘ return_type funotion_name(void); ecify void in its prototype. Object Orienigd Programmi (2010) ntages of Function Prototypes in Prototypes enables the compilers to provide stronger type ch % Because of the usc of prototypes, the compiler conversions between the arguments used to (function's) parameters _ “eee % Because Bi the uae of prototypes, the compiler can also catch differences between the number of arguments used to call a function and the number of parameters in the functions 4 Punction prototypes help to trap bugs before they occur 4 Function prototypes help to verify that the program is wor) functions to be called with mismatched arguments ng | report any questionable type function and the types of ity king correetly by not allowing [Az What do you mean by default argument? With ‘example (2013, 2012) | ‘Ans: Default Argument: A default argument is a value automatically assigned by the compiler if caller of the function doesn’t provide a value for the argument with default value. Example: #include using namespace std; //,A function with default arguments, it can be called with 1! Zarguments or 3 arguments or 4 arguments, provided in function declaration that is int sum(int x, int y, int 2=0, int w=0) { return (x+y +24W); } int main() { : . cout << sum(10, 15) << endl; cout << sum(10, 15, 25) < Hinclude 14; const float pi= float arga(foat n,float b,float h) —— Rage No #138. { float ar, ar=n*bth, Tetum ar; } float arca(float r) f «float ar; ar=pi*r*r; return ar; } float area(float | float b) { float ar; ar=I*b; retum ar, } void main() { = float b.br1; float result; lrscr(); cout<<*\nEnter the Base & Hieght of Triangle: \n”, cin>>b>>h; result=area(0.5,b,h); cout<<“\nArea of Triangle: “<>r; result=area(r); * cout<<“\nArea of Circle: “<>I>>b; result=area(|,b); cout<<“\nArea of Rectangle: “<

You might also like