Page 2 :
Syllabus, Object Oriented Programming using, C++, -------------------------------------------------------Unit I: Object Oriented Programming & C++, Object Oriented Programming Paradigm, Basic Concepts of OOP, Benefits of OOP, Object Oriented, Languages, Applications of OOP, A Simple C++ Program, More C++ Statements, Structure of C++, program., Unit II: Basics of C++, Introduction, Tokens, Keywords, Identifiers & Constants, Basic Data Types, User-defined Data, Types, Derived Data Types, Variables : declaration & dynamic initialization, Reference variables,, Operators in C++ : Scope Resolution, Manipulators, Operator Precedence, Decision Control & Loop, Control Structures: If, If-else, Nested If, Else-if ladder, switch, goto, break statement, while, dowhile, for., Unit III: Functions in C++, Introduction, Function Prototyping, Call by Value & Call by reference, inline function, default, arguments, Function Overloading, Library Functions, Unit IV: Classes & Constructors in C++, Introduction, Structures, Specifying a Class, Defining member functions, Memory allocation for, objects, Static Data Members, Static Member Functions, Objects as Function arguments, Friend, Functions., Introduction to Constructors, Parameterized Constructors, Copy Constructors, Multiple, Constructors in a class, destructors., Unit V: Operator Overloading, Introduction, Defining Operator overloading, Overloading Unary Operators, Overloading binary, operators, overloading binary operator using friend, Rules for overloading operators, Unit VI: Inheritance in C++, Introduction, defining derived classes, single inheritance, multilevel inheritance, multiple, inheritance, hierarchical inheritance, hybrid inheritance, virtual base classes, Abstract classes., Text/Reference Books:1. Object-Oriented Programming with C++ -E-Balgurusamy, 2. The C++ Complete Reference -TMH Publication, 3. Object Oriented Programming in C++ by Robert Lafore, Online References:, 1. www.spoken-tutorial.org free online course of C++
Page 3 :
UNIT I, Object Oriented Programming & C++, -------------------------------------------------------Introduction:, Q: What is OOPs and POP?, Object Oriented Programming (OOP) is an approach to program organization and development, that attempts to eliminate some of the pitfalls of conventional programming methods by, incorporating the best of structured programming features with several powerful new concepts. It, is a new way of organizing and developing programs and has nothing to do with any particular, language. However, not all languages are suitable to implement the OOP concepts easily., Procedure-Oriented Programming:, In the procedure oriented approach, the problem is viewed as the sequence of things to be, done such as reading, calculating and printing such as cobol, fortran and c. The primary focus is on, functions. A typical structure for procedural programming is shown in fig.1.2. The technique of, hierarchical decomposition has been used to specify the tasks to be completed for solving a problem., , Procedure oriented programming basically consists of writing a list of instructions for the, computer to follow, and organizing these instructions into groups known as functions., Some Characteristics exhibited by procedure-oriented programming are:
Page 4 :
• Emphasis is on doing things (algorithms)., • Large programs are divided into smaller programs known as functions., • Most of the functions share global data., • Data move openly around the system from function to function., • Functions transform data from one form to another., • Employs top-down approach in program design., Q: Explain Object Oriented Paradigm, Object Oriented Paradigm The major motivating factor in the invention of object-oriented, approach is to remove some of the flaws encountered in the procedural approach. OOP treats data, as a critical element in the program development and does not allow it to flow freely around the, system. It ties data more closely to the function that operate on it, and protects it from accidental, modification from outside function. OOP allows decomposition of a problem into a number of, entities called objects and then builds data and function around these objects. The organization of, data and function in object-oriented programs is shown in fig.1.3. The data of an object can be, accessed only by the function associated with that object. However, function of one object can access, the function of other objects, , Some of the features of object oriented programming are:, • Emphasis is on data rather than procedure., • Programs are divided into what are known as objects., • Data structures are designed such that they characterize the objects., • Functions that operate on the data of an object are ties together in the data structure. • Data is, hidden and cannot be accessed by external function., • Objects may communicate with each other through function., • New data and functions can be easily added whenever necessary., • Follows bottom up approach in program design., Object-oriented programming is the most recent concept among programming paradigms, and still means different things to different people., Q: What is OOP? Explain characteristics of OOPs?, Basic Concepts of Object Oriented Programming It is necessary to understand some of the, concepts used extensively in object-oriented programming. These include:, • Objects, • Classes
Page 5 :
• Data abstraction and encapsulation, • Inheritance, • Polymorphism, • Dynamic binding, • Message passing, Objects:, Objects are the basic run time entities in an object-oriented system. They may represent a, person, a place, a bank account, a table of data or any item that the program has to handle., Program objects should be chosen such that they match closely with the real-world objects., Objects take up space in the memory and have an associated address like a record in Pascal, or a, structure in C., Although different author represent them differently fig 1.5 shows two notations that are, popularly used in object-oriented analysis and design., , Classes:, We just mentioned that objects contain data, and code to manipulate that data. The entire set, of data and code of an object can be made a user-defined data type with the help of class. In fact,, objects are variables of the type class. Once a class has been defined, we can create any number of, objects belonging to that class. Each object is associated with the data of type class with which they, are created. A class is thus a collection of objects similar types. For examples, Mango, Apple and, orange members of class fruit., If fruit has been defines as a class, then the statement Fruit Mango; will create an object, mango belonging to the class fruit., Data Abstraction:, Abstraction refers to the act of representing essential features without including the background, details or explanation. Classes use the concept of abstraction and are defined as a list of abstract, attributes such as size, wait, and cost, and function operate on these attributes. They encapsulate all, the essential properties of the object that are to be created. The attributes are sometime called data, members because they hold information. The functions that operate on these data are sometimes, called methods or member function.
Page 6 :
Q: Write a short note on Encapsulation., Encapsulation:, The wrapping up of data and function into a single unit (called class) is known as, encapsulation. Data and encapsulation is the most striking feature of a class. The data is not, accessible to the outside world, and only those functions which are wrapped in the class can access, it. These functions provide the interface between the object’s data and the program. This insulation, of the data from direct access by the program is called data hiding or information hiding., Inheritance, Inheritance is the process by which objects of one class acquired the properties of objects of another, classes. It supports the concept of hierarchical classification. For example, the bird, ‘robin’ is a part of, class ‘flying bird’ which is again a part of the class ‘bird’. The principal behind this sort of division, is that each derived class shares common characteristics with the class from which it is derived as, illustrated in fig 1.6., , In OOP, the concept of inheritance provides the idea of reusability. This means that we can add, additional features to an existing class without modifying it. This is possible by deriving a new class, from the existing one. The new class will have the combined feature of both the classes. The real, appeal and power of the inheritance mechanism is that it., Polymorphism, Polymorphism is another important OOP concept. Polymorphism, a Greek term, means the ability to, take more than on form. An operation may exhibit different behaviour is different instances. The, behaviour depends upon the types of data used in the operation, Polymorphism plays an important role in allowing objects having different internal, structures to share the same external interface. This means that a general class of operations may be, accessed in the same manner even though specific action associated with each operation may differ., Polymorphism is extensively used in implementing inheritance., Dynamic Binding, Binding refers to the linking of a procedure call to the code to be executed in response to the, call. Dynamic binding means that the code associated with a given procedure call is not known until
Page 7 :
the time of the call at run time. It is associated with polymorphism and inheritance. A function call, associated with a polymorphic reference depends on the dynamic type of that reference., Message Passing:, A Message for an object is a request for execution of a procedure, and therefore will invoke a, function (procedure) in the receiving object that generates the desired results., Message passing involves specifying the name of object, the name of the function (message) and the, information to be sent, Q: Write a notes on benefits of OOPs., Benefits of OOP, OOP offers several benefits to both the program designer and the user. Object Orientation, contributes to the solution of many problems associated with the development and quality of, software products. The new technology promises greater programmer productivity, better quality, of software and lesser maintenance cost. The principal advantages are:, • Through inheritance, we can eliminate redundant code extend the use of existing, • Classes., • We can build programs from the standard working modules that communicate with one, another, rather than having to start writing the code from scratch. This leads to saving of, development time and higher productivity., • The principle of data hiding helps the programmer to build secure program that cannot be, invaded by code in other parts of a programs., • It is possible to have multiple instances of an object to co-exist without any interference., • It is possible to map object in the problem domain to those in the program., • It is easy to partition the work in a project based on objects., • The data-centered design approach enables us to capture more detail of a model can, implemental form., • Object-oriented system can be easily upgraded from small to large system., • Message passing techniques for communication between objects makes to interface, descriptions with external systems much simpler., • Software complexity can be easily managed., Q: Discuss the Object Oriented Language., Object Oriented Language, Object-oriented programming is not the right of any particular languages. Like structured, programming, OOP concepts can be implemented using languages such as C and Pascal. However,, programming becomes clumsy and may generate confusion when the programs grow large. A, language that is specially id designed to support the OOP concepts makes it easier to implement, them. The languages should support several of the OOP concepts to claim that they are objectoriented. Depending upon the features they support, they can be classified into the following two, categories:, 1. Object-based programming languages, and, 2. Object-oriented programming languages.
Page 8 :
Object-based programming is the style of programming that primarily supports encapsulation and, object identity. Major feature that are required for object based programming are:, • Data encapsulation, • Data hiding and access mechanisms, • Automatic initialization and clear-up of objects, • Operator overloading, Object-oriented programming language incorporates all of object-based programming features along, with two additional features, namely, inheritance and dynamic binding. Object-oriented, programming can therefore be characterized by the following statements:, Object-based features + inheritance + dynamic binding, Q: Write a short note on application of OOPs., Application of OOP, • Real-time system, • Simulation and modelling, • Object-oriented data bases, • Hypertext, Hypermedia, and expert text, • AI and expert systems, • Neural networks and parallel programming, • Decision support and office automation systems, • CIM/CAM/CAD systems, Introduction of C++, C++ is an object-oriented programming language. It was developed by Bjarne Stroustrup at, AT&T Bell Laboratories in Murray Hill, New Jersey, USA, in the early 1980’s. Stroustrup, an admirer, of Simula67 and a strong supporter of C, wanted to combine the best of both the languages and, create a more powerful language that could support object-oriented programming features and still, retain the power and elegance of C., C++ is an extension of C with a major addition of the class construct feature of Simula67., Since the class was a major addition to the original C language, Stroustrup initially called the new, language ‘C with classes’. However, later in 1983, the name was changed to C++. The idea of C++, comes from the C increment operator ++, thereby suggesting that C++ is an augmented version of, C., C+ + is a superset of C. Almost all c programs are also C++ programs. However, there are a, few minor differences that will prevent a c program to run under C++ complier. We shall see these, differences later as and when they are encountered., Q: Explain the difference of C and C++, Q: Explain the difference between OOPs and POP, Difference between C and C++
Page 9 :
SR., No., , 4, , C, C was developed by Dennis Ritchie in, 1969, C is a structural or procedural, programming language., Emphasis is on procedure/algorithm or, steps to solve any problem., Functions are the fundamental building, blocks., , 5, , In C, the data is not secured., , Objects are the fundamental building blocks., Data is hidden and can’t be accessed by, external functions., , 6, , C follows top down approach., , C++ follows bottom up approach, , 1, 2, 3, , C++, C++ was developed by Bjarne Stroustrup in, 1979, C++ is an object oriented programming, language., Emphasis is on objects rather than procedure., , Simple C++ Program, Let us begin with a simple example of a C++ program that prints a string on the screen., #include <iostream.h>, Void main(), {, Cout<< “wel come to C++ Programming”;, }, Program feature, Like C, the C++ program is a collection of function. The above example contain only one, function main(). As usual execution begins at main(). Every C++ program must have a, main(). C++ is a free form language. With a few exception, the compiler ignore carriage, return and white spaces. Like C, the C++ statements terminate with semicolons., Comments C++ introduces a new comment symbol // (double slash). Comment start with a double, slash symbol and terminate at the end of the line. A comment may start anywhere in the line, and, whatever follows till the end of the line is ignored. Note that there is no closing symbol. The double, slash comment is basically a single line comment. Multiline comments can be written as follows:, // This is an example of, // C++ program to illustrate, // some of its features, Output operator, The only statement in program 1.10.1 is an output statement. The statement, Cout<<”C++ is better than C.”;, Causes the string in quotation marks to be displayed on the screen. This statement introduces, two new C++ features, cout and <<. The identifier cout(pronounced as C out) is a predefined object, that represents the standard output stream in C++. Here, the standard output stream represents the
Page 10 :
screen. It is also possible to redirect the output to other output devices. The operator << is called the, insertion or put to operator., Q: write a short note on Iostream file., The iostream File, We have used the following #include directive in the program:, #include <iostream>, The #include directive instructs the compiler to include the contents of the file enclosed, within angular brackets into the source file. The header file iostream.h should be included at the, beginning of all programs that use input/output statements., Return Type of main(), In C++, main () returns an integer value to the operating system. Therefore, every main () in, C++ should end with a return (0) statement; otherwise a warning an error might occur. Since main, () returns an integer type for main () is explicitly specified as int. Note that the default return type, for all function in C++ is int. The following main without type and return will run with a warning, main (), {, ---------------------------}, More C++ Statements Let we consider a slightly more complex C++ program. Assume that we, should like to read two numbers from the keyboard and display their average on the screen. C++, statements to accomplish this is shown in program.
Page 11 :
Q: Explain input/out operator in C++, Q: Explain extraction and insertion operation in C++., Input Operator, The statement, cin >> number1;, Is an input statement and causes the program to wait for the user to type in a number. The, number keyed in is placed in the variable number1. The identifier cin (pronounced ‘C in’) is a, predefined object in C++ that corresponds to the standard input stream. Here, this stream represents, the keyboard., The operator >> is known as extraction or get from operator. It extracts (or takes) the value, from the keyboard and assigns it to the variable on its right fig 1.8. This corresponds to a familiar, scanf() operation. Like <<, the operator >> can also be overloaded., , Q: Explain Structure of C++ Program, Structure of C++ Program, As it can be seen from program 1.12.1, a typical C++ program would contain four sections as, shown in fig. 1.9. This section may be placed in separate code files and then compiled independently, or jointly. It is a common practice to organize a program into three separate files., The class declarations are placed in a header file and the definitions of member functions go, into another file. This approach enables the programmer to separate the abstract specification of the, interface from the implementation details (member function definition). Finally, the main program, that uses the class is places in a third file which “includes: the previous two files as well as any other, file required.
Page 12 :
MCQ, 1. C language has been developed by, a. Martin Richards, b. Bijarne Stroustrup, c. Dennis Ritche, d. Ken Thompson, 2. OOPs stands for--------------a. Object Orion programming, b. Object orientation programming, c. Object opinion programming, d. Object Oriented Programming, 3. POP Stands for -----------------------a. Procedure-Oriented Programming, b. Program orientation programming, c. Process Oriented programming, d. Primitive Oriented programming, 4. Object is a---------------------a. Record time entity, b. Run time entity, c. Current time entity, d. Logical entity, 5. C++ is often called--------a. Object Oriented Programming, b. Procedure-Oriented Programming, c. a and b, d. Not a and b, 6. Class is -------------------a. Collection of member function, b. Collection of data memnebr, c. a and b, d. None of the above, 7. Which of the following concepts means wrapping up of data and functions together?, a. Data abstraction, b. Encapsulation, c. Inheritance, d. Polymorphism, 8. Which of the following provides a reuse mechanism, a. Data abstraction, b. Encapsulation, c. Inheritance, d. Polymorphism, 9. Which of the following is a user defined data type, a. Integer, b. Array
Page 13 :
c. Pointer, d. Class, 10. Which of the following concepts means waiting until runtime to determine which function, to call., a. Data abstraction, b. Encapsulation, c. Inheritance, d. Dynamic binding, 11. Which of the following is the correct header file in C++ program., a. Stdio.h, b. Conio.h, c. Istream.h, d. Iostream.h, 12. Which of the following operator is overloaded for object cout., a. >>, b. <<, c. ++, d. - 13. Which of the following operator is overloaded for object cin., a. >>, b. <<, c. ++, d. - 14. Which of the following statement is correct?, a. Class is an instance of object., b. Object is an instance of a class., c. Class is an instance of data type., d. Object is an instance of data type., 15. Which of the following approach is adapted by C++?, a. Top-down, b. Bottom-up, c. Right-left, d. Left-right
Page 14 :
UNIT II, Basics of C++, -------------------------------------------------------Q: write a short note on C++ Tokens., C++ Tokens, A token is the smallest element of a program that is meaningful to the compiler. Tokens can be, classified as follows:, Keywords, Identifiers, Constants, Q: Explain Keywords in C++., C++ Keywords, A keyword is a reserved word. You cannot use it as a variable name, constant name etc. A list of 32, Keywords in C++ Language which are also available in C language are given below., auto, , break, , case, , char, , const, , continue, , default, , do, , double, , else, , enum, , extern, , float, , for, , goto, , if, , int, , long, , register, , return, , short, , signed, , sizeof, , static, , struct, , switch, , typedef, , union, , unsigned, , void, , volatile, , while, , Q: What is Identifiers? Explain with an example., Identifiers, Symbolic names can be used in C++ for various data items used by a programmer in his program., A symbolic name is generally known as an identifier. The identifier is a sequence of characters taken, from C++ character set. The rule for the formation of an identifier are:, An identifier can consist of alphabets, digits and/or underscores., It must not start with a digit, C++ is case sensitive that is upper case and lower case letters are considered different from, each other., It should not be a reserved word.
Page 15 :
Q: What is Constant? Explain types of Constant., Constants: Constants are also like normal variables. But, only difference is, their values can not be, modified by the program once they are defined. Constants refer to fixed values. They are also called, as literals., Constants may belong to any of the data type.Syntax:, const, data_type variable_name; (or) const data_type *variable_name;, Types of Constants:, 1. Integer constants – Example: 0, 1, 1218, 12482, 2. Real or Floating point constants – Example: 0.0, 1203.03, 30486.184, 3. Octal & Hexadecimal constants – Example: octal: (013 )8 = (11)10, Hexadecimal: (013)16 = (19)10, 4. Character constants -Example: ‘a’, ‘A’, ‘z’, 5. String constants -Example: “Pi Value”, Q: Explain data types in C++., Basic Data Types, C++ supports a large number of data types. The built in or basic data types supported by C++ are, integer, floating point and character. C++ also provides the data type bool for variables that can, hold only the values True and false., , Some commonly used data types are summarized in table along with description.
Page 16 :
User-defined type:, Structure and classes :, The user-defined data type structure and union are same as that of C. while these data types are, legal in C++. C++ also permits us to define another user defined data types known as class. The, class variable are known as objects, which are the central focus of OOPs., Enumerations, As in C, enumerations provide a convenient way to define variables that have only a small set of, meaningful values. Here is a simple example., enum colour {red, green, blue, black};, colour foreground = black;, Strings, C ++ may use the C string functions, where a string is represented by a char*, but they rely on a null, termination and proper memory allocation to hold the string. The C ++ string class attempts to, simplify string manipulation by automating much of the memory allocation and management.
Page 17 :
Derived Data type:, Arrays, An array in c++ is similar to that in c, the only difference is the way character arrays are initialized., In c++, the size should be one larger than the number of character in the string where in c, it is exact, same as the length of string constant., Ex - char string1[3] = “ab”; // in c++, char string1[2] = “ab”; // in c., , Functions, Functions in c++ are different than in c there is lots of modification in functions in c++ due to object, orientated concepts in c++., Pointers:, Pointers are declared & initialized as in c., Ex int * ip; // int pointer, ip = &x; //address of x through indirection c++ adds the concept of constant pointer & pointer to a, constant pointer., Q: Write a short notes on Variables in C++., VARIABLES:, Declaration of variables., C requires all the variables to be defined at the beginning of a scope. But c++ allows the declaration, of variable anywhere in the scope. That means a variable can be declared right at the place of its, first use. It makes the program easier to understand., In order to use a variable in C++, we must first declare it specifying which data type we want it to, be. The syntax to declare a new variable is to write the specifier of the desired data type (like int,, bool, float...) followed by a valid variable identifier., For example:, int a;, float b;, These are two valid declarations of variables. The first one declares a variable of type int with, the identifier a. The second one declares a variable of type float with the identifier b . Once 18, declared, the variables a and b can be used within the rest of their scope in the program., Dynamic initialization of variables., In c++, a variable can be initialized at run time using expressions at the place of declaration., This is referred to as dynamic initialization., Ex int m = 10;, Here variable m is declared and initialized at the same time.
Page 18 :
Q: Explain Reference variables., Reference variables:, C++ introduce new kind of variable is known as the Reference Variable. A reference variable, provides an alias for a previously defined variable. Example:- If we make the variable sum a, reference to the variable total, then sum & total can be used interchangeably to represent that, variable. Reference variable is created as, data type & reference name = variable name., Ex:, , int sum = 200;, int &total = sum;, , Here total is the alternative name declared to represent the variable sum. Both variable refer, to the same data object in memory., A reference variable must be initialized at the time of declaration. C++ assigns additional, meaning to the symbol. &..Here & is not an address operation. The notation int & means reference, to int. A major application of reference variable is in passing arguments to functions., EX., Void fun(int &x), {, x=x+10;, }, Void main(), {, int n=10;, fun(n);, }, When the function call fun (n) is executed, it will assign x to n i.e. int &x = n; Therefore x and, n are aliases & when function increments x. n is also incremented. This type of function call is called, call by reference., Q: Explain operators in C++ with example., Operators in c++:, Some of the new operators in c++ are1. :: Scope resolution operators., 2. ::* pointer to member decelerator., 3. * pointer to member operator, 4. .* pointer to member operator., 5. delete memory release operator., 6. endl Line feed operator, 7. new Memory allocation operator., 8. stew Field width operator
Page 19 :
Q:Write a short note on Scope resolution operator., Scope resolution Operator., C++ is a block - structured language. The scope of the variable extends from the point of its, declaration till the end of the block containing the declaration. Consider following program., , The two declaration of x refer to two different memory locations containing different values. Blocks, in C++ are often nested. Declaration in an inner block hides a declaration of the same variable in an, outer block., In C, the global version of a variable cannot be accessed from within the inner block. C++ resolves, this problem by using scope resolution operator (::), because this operator allows access to the global, version of a variable., #include <iostream.h>, int m=10;, int main(), {, int m=20;, {, int k=m;, int m=30;, cout<< “we are in inner block”;, cout<<”k=”<<k<<endl;, cout<<”m=”<<m<<endl;, cout<<”::m=”<<::m<<endl;, }, cout<< “we are in outer block”;, cout<<”m=”<<m<<endl;, cout<<”::m=”<<::m<<endl;, return 0;, }
Page 20 :
In the above program m is declared at three places. And ::m will always refer to global m. A major, application of the scope resolution operator is in the classes to identify the class to which a member, functions belongs., Q: Explain Manipulators in C++., Manipulators:, Manipulators are operators that are used to format the data display. There are two important, manipulators., 1) endl, 2) stew, endl : This manipulator is used to insert a linefeed into an output. It has same effect as using .\n. for, newline., Ex cout<< .a. << a << endl <<.n=. <<n;, << endl<<.p=.<<p<<endl;, The output is, a = 2568, n = 34, p = 275, Setw : With the stew, we can specify a common field width for all the numbers and force them to print, with right alignment., EX cout<<stew (5) <<sum<<endl;, The manipulator setw(5) specifies a field width of 5 for printing the value of variable sum the value, is right justified., , Operator precedence:
Page 21 :
Decision Control & Loop Control Structures:, Q: What is Decision making Statement? Explain if, if—else statement with example., If Statement:, The if statements allows branching (decision making) depending upon the value or state of variables. This, allows statements to be executed or skipped, depending upon decisions. The basic format is,, if (expression), {, Program statement;, }, , Example:, if( students < 65 ), {, ++student_count;, }, In the above example, the variable student_count is incremented by one only if the value of the integer variable, students is less than 65., Program: Write a program find maximum number between two number., Ex: find a maximum number between two numbers, #include<iostream.h>, #include<conio..h>, Void main(), {, int a=10, int b=20;, if(a>b), {, Cout<< “A is Maximum”<<endl;, }, getch();, }
Page 22 :
If-Else statement:, An if statement can be followed by an optional else statement, which executes when the Boolean expression, is false., The general format for these are,, if( condition 1 ), statement1;, else if( condition 2 ), statement2;, else if( condition 3 ), statement3;, else, statement4;, The else clause allows action to be taken where the condition evaluates as false (zero)., Program: : Write a program to find a maximum number between two numbers, Ex: find a maximum number between two numbers, , #include<iostream.h>, #include<conio..h>, Void main(), {, int a=10, int b=20;, if(a>b), {, Cout<< “A is Maximum”<<endl;, }, Else, {, Cout<< “A is Maximum”<<endl;, }, getch();, }
Page 24 :
cout<<"number2 is Maximum \n"<<endl;;, }, Else, {, cout<<"number3is Maximum \n"<<endl;;, }, }, }, Q: Explain Else-If ladder., Else-if ladder:, An if statement can be followed by an optional else if...else statement, which is very useful to test, various conditions using single if...else if statement. When using if…else if…else statements, there are few, points to keep in mind:, , Example:, , , , An if can have zero or one else's and it must come after any else if's., , , , An if can have zero to many else if's and they must come before the else., , , , Once an else if succeeds, none of the remaining else if's or else's will be tested., , #include<iostream.h>, #include<conio.h>, main(), { int invalid_operator = 0;, char operator;, float number1, number2, result;
Page 25 :
cou<<"Enter two numbers and an operator in the format\n");, cou<<number1 operator number2\n";, cin>>number1>>operator>>number2;, if(operator == '*'), result = number1 * number2;, else if(operator == '/'), result = number1 / number2;, else if(operator == '+'), result = number1 + number2;, else if(operator == '-'), result = number1 - number2;, else, invalid_operator = 1;, if( invalid_operator != 1 ), cout<<"%f %c %f is %f\n", number1, operator, number2, result );, else, cou<<"Invalid operator.\n";, }, getch(); }, , Q: Explain Switch statement with example., Switch Statement:, The switch statement:- C provide multiway decision statement known as a switch. The switch statement, tests the value of a given variable (or expression) against a list of case values and when a match is found , a, block of statements associated with case is executed. The general form of the switch statement is as shown, below:, switch(expression), {, case value-1:, block-1;, break;, case value-2:, block-2;, break;, ……
Page 26 :
default:, default- block-;, break;, } Statement-x;, The expression is an integer expression or characters. Value-1,value-2….. are constants or constant, expressions and are known as case labels. Block-1,block-2 ….. are statement lists and mat contain zero or, more statements. Note that case labels end with a colon (:)., The default is an optional case. When present, it will be executed if the value of the expression does, not match with any of case values. if not present, no action takes place if all matches fail and the control, goes to the statement-x., Program: Write a program on switch statement., Example:, void main(), {, int a; /* variable declration */, clrscr();, cou<<Enter Week day no = ";, cin>>a;, switch(a) /*test expression*/, {, case 1:, cou<<”Sunday";, break;, case 2:, cou<<”Monday";, break;, case 3:, cout<<”Tuesday";, break;, case 4:, cout<<Wednesday";, break;, case 5:, cout<<Thrusday";, break;
Page 27 :
case 6:, cout<<Friday";, break;, case 7:, cout<<Staturday";, break;, default:, cout<<Wrong Day NO Insert.";, }, getch();, }, Q: Write a short note on Break statement., THE BREAK STATEMENT, The break statement is used to force fully terminate loops or to exit from a switch. It can be used within a, while, a do-while, for or a switch statement. The format is simple as, break;, Without any embedded expression or statements. The break statement causes a transfer of control out of the, entire switch statement, to the first statement following the switch statement., f a break statement is included in a while, in do while or in for loop, then control will immediately be, transferred out of the loop when the break statement is encountered. Thus provides a convenient way to, terminate the loop if an error or other irregular condition is detected. Let us consider a program segment of, break statement in while loop., , main(), {, int x, sum=Ο;, cout<<Enter any number”);, cin>>x;, while(x<=50), {, if (x<zero), {, cout<<error value because of negative value”);, break;, }
Page 28 :
Cin>>x;, }, Q: Write a short note on Continue statement., The continue statement, The continue statement is used to bypass the remainder of the current pass through a loop. The loop does not, terminate when a continue statement is encountered, instead the remaining loop statements are skipped and, the computation proceeds directly to the next pass through the loop. It can also be included within a while, do, while or a for statement as like break statement. It is also written simply as, Continue;, Without any embedded statement or expression., Example:, int main (), {, /* local variable definition */, int a = 10;, /* do loop execution */, do, {, if( a == 15), {, /* skip the iteration */, a = a + 1;, continue;, }, cout<<"value of a=”<<a;, a++;, }while( a < 20 );, return 0;}, , Q: Write a short note on go to statement., THE GOTO STATEMENT, The goto statement is used to alter the normal sequence of program execution by transferring control to some, other part of the program. It is written as, goto label;
Page 29 :
Where label is an identifier used to label the target statement to which control will be transferred. Control may, be transferred to any other statement within the program. The target statement must be labeled, and the label, must be followed by a colon. Thus the target statement will appear as, Label : statement, No two statements cannot have the same label, Goto statements has many advantages like branching around statements or groups of statements under certain, conditions, jumping to the end of a loop under certain conditions, thus bypassing the remainder of the loop, during the current pass, jumping completely out of a loop under certain conditions, thus terminating the, execution of a loop., , Example, int main (), {, /* local variable definition */, int a = 10;, /* do loop execution */, LOOP: do, {, if( a == 15), {, /* skip the iteration */, a = a + 1;, goto LOOP;, }, Cou<<a;, a++;, }while( a < 20 );, return 0;, }, , Q: Explain while loop with suitable example., While loop:, A while loop in C++ programming repeatedly executes a target statement as long as a given condition is, true., Syntax
Page 30 :
The syntax of a while loop in C++ programming language is:, , Here, statement(s) may be a single statement or a block of statements., The condition may be any expression, and true is any nonzero value. The loop iterates while the, condition is true., When the condition becomes false, the program control passes to the line immediately following the, loop., , Q: Write a program to show 0 to 50 numbers on screen., Example:, main(), {, int x = 0, cou<<“Print 0 to 50 numbers”;, while(x>=50), {, Cout<<x;, x ++ ;, }, }, , Q: Explain Do-while loop with suitable example., , Do-While loop:, Unlike for and while loops, which test the loop condition at the top of the loop, the do...while loop in, C programming checks its condition at the bottom of the loop., A do...while loop is similar to a while loop, except the fact that it is guaranteed to execute at least, one time., Syntax, The syntax of a do...while loop in C++ programming language is:
Page 31 :
int main (), {, /* local variable definition */, int a = 1;, /* do loop execution */, do, {, Cout<<"value of a:="<< a);, a = a + 1;, }while( a <= 50 );, return 0;, }, , Q: Explain For loop with suitable example., , For loop:, A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a, specific number of times., Syntax, The syntax of a for loop in C programming language is:, , Here is the flow of control in a ‘for’ loop:, 1. The init step is executed first, and only once. This step allows you to declare and initialize, any loop control variables. You are not required to put a statement here, as long as a, semicolon appears.
Page 32 :
2. Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the, body of the loop does not execute and the flow of control jumps to the next statement just, after the ‘for’ loop., 3. After the body of the ‘for’ loop executes, the flow of control jumps back up to the increment, statement. This statement allows you to update any loop control variables. This statement, can be left blank, as long as a semicolon appears after the condition., 4. The condition is now evaluated again. If it is true, the loop executes and the process repeats, itself (body of loop, then increment step, and then again condition). After the condition, becomes false, the ‘for’ loop terminates., Program: Write a program to calculate factorial of a given number., Example:, main(), {, int i = 1;, int fact=1;, int n;, cout<<“Enter the Factorial number”;, cin>>n;, for(i=1;i>=n;i++), {, fact=fact*i;, i++ ;, }, Cout<<x;, }, , MCQ, 1. Which is not a C++ tokens, a. Keywords, b. Identifiers, c. Data Types, d. Program, 2. Identifier is-----------a. Name of entity, b. Function, c. Pointer, d. Data
Page 33 :
3. Constant is ----------------- during execution of program, a. Changing value, b. Does not changing value, c. Exchange value, d. Varies value, 4. Variable is ----------------- during execution of program, a. Does not changing value, b. Exchange value, c. Varies value, d. Constant value, 5. Which not a data type in c++, a. Built in data type, b. Derive data type, c. Operative data type, d. Primitive data type, 6. Which is user defined data type, a. Enum, b. Pointer, c. Array, d. String, 7. Scope resolution operator symbol is, a. :;, b. ::, c. ::*, d. ::->, 8. Keywords are-------a. Special word, b. Reserved word, c. Constant word, d. None of the above, 9. Which is built in datatype, a. String, b. Array, c. Double, d. Reference, 10. C++ programming depend upon----a. Algorithm, b. Method, c. Function & data, d. Procedure
Page 34 :
UNIT III, Functions in C++, -------------------------------------------------------Introduction:, C++ functions are basic building blocks in a program. All C++ programs are written using functions, to improve re-usability, understand ability and to keep track on them., Q: What is Function? Explain types of function., Definition of function,, A large C++ program is divided into basic building blocks called C function. C function contains set, of instructions enclosed by “{ }” which performs specific operation in a C program. Actually, Collection of, these functions creates a C program., Def: “Function is a self-contained block”., The general form of a function definition in C programming language is as follows −, return_type function_name( parameter list ), {, Body of the function, }, A function definition in C programming consists of a function header and a function body. Here are, all the parts of a function −, Return Type − A function may return a value. The return_type is the data type of the value the function, returns. Some functions perform the desired operations without returning a value. In this case, the return_type, is the keyword void., Function Name − This is the actual name of the function. The function name and the parameter list, together constitute the function signature., Parameters − A parameter is like a placeholder. When a function is invoked, you pass a value to the, parameter. This value is referred to as actual parameter or argument. The parameter list refers to the type,, order, and number of the parameters of a function. Parameters are optional; that is, a function may contain no, parameters., Function Body − The function body contains a collection of statements that define what the function, does.
Page 35 :
Return values and their types,, All C++ functions can be called either with arguments or without arguments in a C++ program. These, functions may or may not return values to the calling function. Now, we will see simple example C programs, for each one of the below., , , C++ function with arguments (parameters) and with return value., , , , C++ function with arguments (parameters) and without return value., , , , C++ function without arguments (parameters) and without return value., , , , C++ function without arguments (parameters) and with return value., , With arguments and with return values, Function declaration:, int function ( int );, function call: function ( a );, function definition:, int function( int a ), {, statements;, return a;, }, , 2. With arguments and without return values:, function declaration:, void function ( int );, function call: function( a );, function definition:, void function( int a ), {, Statements;, }, 3. Without arguments and without return values, function declaration:, void function();, function call: function();, function definition:, void function()
Page 36 :
{, statements;, }, , 4. Without arguments and with return values:, function declaration:, int function ( );, function call: function ( );, function definition:, int function( ), {, statements;, return a;, }, , Function Declarations, A function declaration tells the compiler about a function name and how to call the function. The actual, body of the function can be defined separately., A function declaration has the following parts −, return_type function_name( parameter list );, For the above defined function max(), the function declaration is as follows −, int max(int num1, int num2);, Parameter names are not important in function declaration only their type is required, so the following, is also a valid declaration −, int max(int, int);, Function declaration is required when you define a function in one source file and you call that function, in another file. In such case, you should declare the function at the top of the file calling the function., Calling a Function, While creating a C function, you give a definition of what the function has to do. To use a function,, you will have to call that function to perform the defined task., When a program calls a function, the program control is transferred to the called function. A called, function performs a defined task and when its return statement is executed or when its function-ending closing, brace is reached, it returns the program control back to the main program.
Page 37 :
To call a function, you simply need to pass the required parameters along with the function name, and, if the function returns a value, then you can store the returned value., For example −, #include <iostream.h>, /* function declaration */, int max(int num1, int num2);, int main () {, /* local variable definition */, int a = 100;, int b = 200;, int ret;, /* calling a function to get max value */, ret = max(a, b);, cout"Max value is :", ret ;, return 0;, }, /* function returning the max between two numbers */, int max(int num1, int num2) {, /* local variable declaration */, int result;, if (num1 > num2), result = num1;, else, result = num2;, return result;, }, HOW TO CALL C FUNCTIONS IN A PROGRAM?, There are two ways that a C++ function can be called from a program. They are,, , , , Call by value, Call by reference, , Q: Explain Call by Value with example., 1. CALL BY VALUE:
Page 38 :
, , , , In call by value method, the value of the variable is passed to the function as parameter., The value of the actual parameter cannot be modified by formal parameter., Different Memory is allocated for both actual and formal parameters. Because, value of actual, parameter is copied to formal parameter., , Note:, Actual parameter – This is the argument which is used in function call., Dummy parameter – This is the argument which is used in function definition, EXAMPLE PROGRAM FOR C++ FUNCTION (USING CALL BY VALUE):, In this program, the values of the variables “m” and “n” are passed to the function “swap”., These values are copied to formal parameters “a” and “b” in swap function and used, #include<stdio.h>, // function prototype, also called function declaration, void swap(int a, int b);, int main(), {, int m = 22, n = 44;, // calling swap function by value, Cout<<" values before swap m =”<<m<<”n = ",<< n;, swap(m, n);, }, void swap(int a, int b), {, int tmp;, tmp = a;, a = b;, b = tmp;, Cout<<" values after swap m =”<<a<<”n = ",<< b;, , }, OUTPUT:, values before swap m = 22, and n = 44, values after swap m = 44, and n = 22
Page 39 :
Q: Explain Call by Value with example., CALL BY REFERENCE:, , , In call by reference method, the address of the variable is passed to the function as parameter., , , , The value of the actual parameter can be modified by formal parameter., , , , Same memory is used for both actual and formal parameters since only address is used by both, parameters., , EXAMPLE PROGRAM FOR C++ FUNCTION (USING CALL BY REFERENCE):, , , In this program, the address of the variables “m” and “n” are passed to the function “swap”., , , , These values are not copied to formal parameters “a” and “b” in swap function., , , , Because, they are just holding the address of those variables., , , , This address is used to access and change the values of the variables., , Program: Write a program Swap/Exchange between two numbers, #include<iostream.h>, // function prototype, also called function declaration, void swap(int *a, int *b);, int main(), {, int m = 22, n = 44;, // calling swap function by reference, Cout<<" values before swap m =”<<m<<”n = ",<< n;, swap(&m, &n);, }, void swap(int *a, int *b), {, int tmp;, tmp = *a;, *a = *b;, *b = tmp;, Cout<<" values after swap a =”<<*a<<”n = ",<< *b;, }, OUTPUT:, values before swap m = 22, and n = 44, values after swap a = 44, and b = 22
Page 40 :
Q: Write a short notes on inline function., Inline function:, The inline specifier indicates the compiler that inline substitution is preferred to the usual function, call mechanism for a specific function. This does not change the behaviour of a function itself, but, is used to suggest to the compiler that the code generated by the function body is inserted at each, point thefunction is called, instead of being inserted only once and perform a regular call to it,, which generally involves some additional overhead in running time., The format for its declaration is:, inline type name ( arguments ... ) { instructions ... }, and the call is just like the call to any other function. You do not have to include the inline, keyword when calling the function, only in its declaration. Most compilers already optimize code, to generate inline functions when it is more convenient. This specifier only indicates the compiler, that inline is preferred for this function., Program: Write a program to calculate square of numbers, #include <iostream.h>, inline float square( float a), {, a=a*a;, cou<<a<<endl:, }, , int main(), {, Float b;, b=square(a);, return 0;, }, Q: Write a short note on default arguments., Default arguments:, When declaring a function we can specify a default value for each parameter. This value will, be used if the corresponding argument is left blank when calling to the function. To do that, we, simply have to use the assignment operator and a value for the arguments in the function
Page 41 :
declaration. If a value for that parameter is not passed when the function is called, the default value, is used, but if a value is specified this default value is ignored and the passed value is used instead., Program: Write a program to calculate Area of circle., #include<iostream.h>, Void area( float r, float p=3.14), { int a;, a=p*r*r;, cout<<”Area of circle=”<<a<<endl;, }, Void main(), {float x;, x=area(5);, }, Q: What is function overloading? Explain with suitable example, Function Overloading:, In C++ two different functions can have the same name if their parameter types or number, are different. That means that you can give the same name to more than one function if they have, either a different number of parameters or different types in their parameters., For example:, // overloaded function, #include <iostream>, using namespace std;, int operate (int a, int b), {, return (a*b);, }, float operate (float a, float b), {, return (a/b);, }, int main (), {, int x=5,y=2;, float n=5.0,m=2.0;, cout << operate (x,y);, cout << "\n";, cout << operate (n,m);, cout << "\n";, return 0;, }
Page 42 :
The output is :, , 10, 2.5, In this case we have defined two functions with the same name, operate, but one of them, accepts two parameters of type int and the other one accepts them of type float. The compiler knows, which one to call in each case by examining the types passed as arguments when the function is, called. If it is called with two ints as its arguments it calls to the function that has two int parameters, in its prototype and if it is called with two floats it will call to the one which has two float parameters, in its prototype., Q: Write a short note on Library function., Library Functions:, C ++ provides many built in functions that saves the programming time., Mathematical Functions, Mathematical functions like sin ( ), cos ( ), etc. are defined in header file math.h. Some of the, important mathematical functions are given in the following table., , Character Functions, All the character functions require ctype.h header file. The following table lists the function.
Page 43 :
String Functions, The string functions are present in the string.h header file. Some string functions are given below:, , MCQ, 1. Which of the following concept of oops allows compiler to insert arguments in a function, call if it is not specified?, a. Call by value, b. Call by reference, c. Default argument, d. Call by pointer, 2. Which of the following is correct about function overloading?
Page 44 :
a. The types of arguments are different, b. The order of arguments is different, c. The number of arguments is same, d. Both a and b, 3. One line function is ------------------a. Normal function, b. Friend function, c. Inline function, d. Virtual function, 4.
Page 45 :
UNIT IV, Classes & Constructors in C++, -------------------------------------------------------Introduction:, C++ supports the object-oriented features directly. All these features like Data abstraction,, Data encapsulation, Information hiding etc have one thing in common – the vehicle that is used to, implement them. The vehicle is “ class.”, Q: What is Class and Object? Explain with suitable example., Class:, Class is a user defined data type just like structures, but with a difference. It also has three, sections namely private, public and protected. Using these, access to member variables of a class, can be strictly controlled., The following is the general format of defining a class template:, class class_name, {, Private:, Variable declaration;, Function declaration;, Private:, Variable declaration;, Function declaration;, }, The keyword class is used to define a class template. The private and public sections of a, class are given by the keywords ‘private’ and ‘public’ respectively. They determine the accessibility, of the members. All the variables declared in the class, whether in the private or the public section,, are the members of the class. Since the class scope is private by default, you can also omit the, keyword private. In such cases you must declare the variables before public, as writing public, overrides the private scope of the class, Example:, class add, {
Page 46 :
Private:, int a;, int b;, Private:, Void getdata( );, Void putdata( );, }, , Creating Object:, Once a class is declared, an object of that type can be defined. An object is said to be a specific, instance of a class just like Maruti car is an instance of a vehicle or pigeon is the instance of a bird., Once a class has been defined several objects of that type can be declared. For instance, an object of, the class defined above can be declared with the following statement:, Syntax:, Class Class_Name object Name;, Example:, Class Maruti Swift;, Or, Maruti Swift;, Once the object is declared, its public members can be accessed using the dot operator with the, name of the object., Object-name.function-name(actual-arguments);, Ex, Swift.getdata( shape,color);, , Q: How to explain Member function definition, Member function definition, Member function can be defined in two ways:, (i) Inside the class, (ii) Outside the class, Inside the class : When a member function is defined inside a class, it is considered to be inline by, default. If a member function is very small then it should be defined inside the class., The class declaration of previous program will be as follow:, class student, {, char name [ 20 ];, int rn ;, float marks ;
Page 47 :
public :, void getdata ( ), {, cin >> name >> m >> marks ;, }, void putdata ( ), {, cout << name << rn << marks :, }, };, , Outside the class :, When a function has larger code then it should be defined outside the class declaration. The, prototype of such functions, however, must be provided in the class definition. The operator ‘: :’, known as scope resolution operator is used to associate member functions to their corresponding, class., The format is :, return_tyoe class-name::function_name( argument declaration), {, , function body, , }, The membership label class name:: tells the compiler that the function name belongs to the class, name. That is the scope of the function id restricted to the class name specified in the header line., The symbol :: is called the scope resolution operator. For instance, consider the member function, getdata() and putdata are discussed above. They may be codded as follows:, void getdata ( ), {, cin >> name >> m >> marks ;, }, void putdata ( ), {, cout << name << rn << marks :, }, Q: Explain Memory allocation for objects., Memory allocation for objects:, We have stated that the memory space for objects is allocated when they are declared and not when, the class is specified. This statement is only partly true. Actually, the member function are created, and placed in the memory space only once they are defined as a part of a class specification. Separate, memory location for the objects are essential, because the member variables will hold different data, values for different objects. This is shown in figure
Page 48 :
Q: What is Static data members? Explain with suitable example., Static Data Members:, A data member of a class can be qualified as static. The properties of a static member variable, are similar to that of C static variable. A static member variable has certain special characteristics., These are:, Ii is initialized to zero when the first objects of its Class is created. No other, initialization is permitted., Only one copy of that member is created for the entire class and is shared by all the, objects of that class, no matter how many objects are created., It is visible only within the class, but its lifetime is the entire program., Static variables are normally used to maintain values common to the entire class. For Eg., a, static data member can be used as a counter hat records the occurrences of all the objects., Example:, # include <iostream.h>, Class count, {, Static int c;, int a;, public:, Void getdat(), {, Cin>>a;, C++;, }, Void putdata()
Page 50 :
}, Void main(), {, Stat s1,s2;, S1.getdat();, S1.showdata();, Stat:: Showcount():, S2.getdata();, S2.showdata();, Stat:: Showcount():, }, Q: Explain objects as function arguments., Objects as function Arguments:, The objects of a class can be passed as arguments to member functions as well as nonmember, functions either by value or by reference. When an object is passed by value, a copy of the actual, object is created inside the function. This copy is destroyed when the function terminates. Moreover,, any changes made to the copy of the object inside the function are not reflected in the actual object., On the other hand, in pass by reference, only a reference to that object (not the entire object) is passed, to the function. Thus, the changes made to the object within the function are also reflected in the, actual object., Example: A program to demonstrate passing objects by value to a member function of the same, class, #include <iostream>, using namespace std;, class Convert, {, float cm, m;, public :, void input(), {, cout << "\n \t Please enter value in meter to convert in centimeter : ";, cin >> m;, }, void conv_cm(Convert obj), {, obj.cm=obj.m*100;, cout << "\n \t In centimeter : " << obj.cm;, }, };, int main (), {, Convert obj1, obj2;, obj1.input();, obj1.conv_cm(obj1);
Page 51 :
obj2.input();, obj2.conv_cm(obj2);, cout << "\n";, return 0;, }, Q: What is friend function? Explain with suitable example., Friend Function:, C++ allows the common function to make friendly with the both classes, thereby allowing the, function to have access to the private data of these classes. Such function need not be a member of, classes., The function declaration should be preceded by the keyword friend. The function is defined, elsewhere in the program like a normal C++ function. The function definition does not use either, the keyword friend or the scope operator .The functions that are declared with the keyword friend, are known as friend functions. A function can be declared as a friend in any number of classes. A, friend function, although not a member function, has full access rights to the private members of, the class., To make an outside function ""friendly* to a class, we have to simply declare this function as a friend, of the class as shown below;, Class ADC, {, itlii, publ i c ;, friend void xyz{vo1d)? // declaration, , }, A friend function possesses certain special characteristics:, , , It is not in the scope of the class to which it has been declared as friend., , , , Since it is not in the scope of the class, it cannot be called using the object of that class,, , , , It can be invoked like a normal function without the help of any object,, , , , Unlike member functions, it cannot access the member names directly and has to use an, object name and Hot membership Operator with each member name, , , , It can be declared either in the public or the private part of a class without affect- ing its, meaning.
Page 52 :
, , Usually, it has the objects as erguments- Thc friend functions are often used in operator, overloading which will be discussed later., , Example:, #include<iostream.h>, #include<conio.h>, Class sample, Q: What is Constructor? Explain types of constructor., Constructor:, A constructor is a 'special' member function whose task is to initialize the objects of its class., It is special because its name is the same as the class name. The constructor is invoked whenever an, object of its associated class is created. It is called constructor because it constructs the values data, members of the class., A constructor is declared and denned as follows:, // class with a constructor, class Integer, int m, n:, publ ic:, integer(void) ; // constructor declared, -----------};, , When a class contains a constructor like the one defined above, it is guaranteed that an object created, by the class will be initialized automatically. For example, the declaration, Integer int l; // object int l created, Not only creates the abject in! I oi' typr integer but also initializes its data members iti and n to zero, There is no need to write any statement to invoke the constructor function (as. we do with the, normal member functions). If a 'normal' member function is defined for zero initialization, we, would need to invoke this function for each of the objects separately. This would be very, inconvenient, if there are a large number of objects.
Page 53 :
A constructor that accepts no parameters is called the default conxtructur. The default constructor, for class A is A::A( ). If no such constructor is defined, then the compiler supplies a default, constructor, therefore a statement such as:, A a;, Invokes the default constructor of the compiler to create the object a., The constructor functions have some special characteristics, These are ;, • They should be declared in the public section,, • They arc invoked automatically when the objects are created., • They do not have return types, not even void and therefore, and they cannot return values., • They cannot be inherited, though a derived class can call the base class constructor, • Like other C++ functions, they can have default arguments., • Constructors cannot be virtual., • We cannot refer to their addresses,, • An object with a constructor (or destructor) cannot be used as a member of a union., • They make implicit calls' to the operators new and delete when memory allocation is, required., Q;Write a short notes on Default Constructor., Default Constructor:, Default Constructor is also called as Empty Constructor which has no arguments and It is, Automatically called when we creates the object of class but Remember name of Constructor is, same as name of class and Constructor never declared with the help of Return Type. Means we, cant Declare a Constructor with the help of void Return Type. , if we never Pass or Declare any, Arguments then this called as the Copy Constructors., Example:, #include <iostream>, using namespace std;, class Employee, {, public:, Employee(), {, cout<<"Default Constructor Invoked"<<endl;, }
Page 54 :
};, int main(void), {, Employee e1; //creating an object of Employee, Employee e2;, return 0;, }, Parameterized Constructor: - This is Another type Constructor which has some Arguments and, same name as class name but it uses some Arguments So For this We have to create object of Class, by passing some Arguments at the time of creating object with the name of class. When we pass, some Arguments to the Constructor then this will automatically pass the Arguments to the, Constructor and the values will retrieve by the Respective Data Members of the Class., Example:, #include <iostream>, using namespace std;, class Employee {, public:, int id;//data member (also instance variable), string name;//data member(also instance variable), float salary;, Employee(int i, string n, float s), {, id = i;, name = n;, salary = s;, }, void display(), {, cout<<id<<" "<<name<<" "<<salary<<endl;, }, };, int main(void) {, Employee e1 =Employee(101, "Sonoo", 890000); //creating an object of, Employee, Employee e2=Employee(102, "Nakul", 59000);, e1.display();, e2.display();, return 0;, }, Q: Explain copy constructor with an example., Copy Constructor:This is also another type of Constructor. In this Constructor we pass the object of class into, the Another Object of Same Class. As name Suggests you Copy, means Copy the values of one, Object into the another Object of Class .This is used for Copying the values of class object into an, another object of class So we call them as Copy Constructor and For Copying the values We have
Page 55 :
to pass the name of object whose values we wants to Copying and When we are using or passing, an Object to a Constructor then we must have to use the & Ampersand or Address Operator., Example:, #include<iostream>, #include<conio.h>, using namespace std;, class Example {, // Variable Declaration, int a, b;, public:, //Constructor with Argument, Example(int x, int y) {, // Assign Values In Constructor, a = x;, b = y;, cout << "\nIm Constructor";, }, void Display() {, cout << "\nValues :" << a << "\t" << b;, }, };, int main() {, Example Object(10, 20);, //Copy Constructor, Example Object2 = Object;, // Constructor invoked., Object.Display();, Object2.Display();, // Wait For Output Screen, getch();, return 0;, }, Q: What is Constructor? Explain constructor overloading.
Page 56 :
Multiple Constructor:, In C++, We can have more than one constructor in a class with same name, as long as each has a, different list of arguments. This concept is known as Constructor Overloading and is quite similar, to function overloading., Overloaded constructors essentially have the same name (name of the class) and different, number of arguments., A constructor is called depending upon the number and type of arguments passed., While creating the object, arguments must be passed to let compiler know, which constructor, needs to be called., #include <iostream>, using namespace std;, class construct, {, public:, float area;, // Constructor with no parameters, construct(), {, area = 0;, }, // Constructor with two parameters, construct(int a, int b), {, area = a * b;, }, void disp(), {, cout<< area<< endl;, }, };, int main(), {, // Constructor Overloading, // with two different constructors, // of class name, construct o;, construct o2( 10, 20);, o.disp();, o2.disp();
Page 57 :
return 1;, }, Q: What is Destructor? Explain with suitable example., Destructor:, A destructor as the name implies, is used to the objects that have been created by a constructor. Like, a constructor, the destructor is a member function whose name is the same as the class name but is, preceded by a tilde. The destructor for the class student can be defined as shown below:, ~student();, Example ;, Class abc, {, Public:, abc( ), {, Cout<< “Call constructor”;, }, ~abc( ), {, Cout<< “call destructor”;, }, , }, , MCQ, 1. Which of the following is an abstract data type?, a. int, b. string, c. class, d. float, 2. Which of the following term is used for a function defined inside a class?, a. Data member, b. Member function, c. Class function, d. Classic function, 3. Which of the following is not the member of class?, a. Static function, b. Friend function, c. Const function, d. Virtual function, 4. Which of the following cannot be friend?, a. Function, b. Class
Page 58 :
c. Object, d. Operator function, 5. Which of the following statement is correct, a. A constructor is called at the time of declaration, b. A constructor is called at the time of use of an object, c. A constructor is called at the time of declaration of a class, d. A constructor is called at the time of use of class, 6. Which of the following functions are performed by a constructor?, a. Construct a new class, b. Construct a new object, c. Construct a new function, d. Initialize objects, 7. Which of the following access specifier is used as a default in a class definition?, a. Protected, b. Public, c. Private, d. Friend, 8. What is correct about the static data member of a class?, a. A static member function can access only static data members of a class., b. A static data member is shared among all the object of the class., c. A static data member can be accessed directly from main()., d. Both A and B., 9. Which of the following statement is correct, a. Class is an instance of object., b. Object is an instance of a class., c. Class is an instance of data type., d. Object is an instance of data type., 10. Which of the following is not a type of constructor?, a. Copy constructor, b. Friend constructor, c. Default constructor, d. Parameterised constructor
Page 59 :
UNIT V, Operator Overloading, -------------------------------------------------------Introduction:, Overloading means assigning different meaning to an operation depending on the context., C++ permits overloading of operators, thus allowing us to assign multiple meanings to the, operators., Q: What is an operating overloading? Explain with suitable example., Defining operator overloading:, To define an additional task to an operator, we must specify what it means in relation to the, class to which the operator is applied. This is done with the help of a special function, called operator, function, which describe the task. The general form of an operator function is, Return type class-name:: operator op(arglist), {, Function body, }, Where return type is the type of value returned by the specified operation and op is the operating, being overloaded. The op is preceded by the keyword operator. Operator op os the function name., Q: What is an operating overloading? Explain overloading unary operator with suitable example., , Overloading Unary Operator:, A minus operator when used as a unary, takes just one operand. We know that this operator changes, the sign of an operand when applied to a basic data item. To overload this operator so that it can be, applied to an objecct in much the same way is applied to an int or float variable. The unary minus, when applied to an object should change the sign of each of its data items., , Class opr, {, Private:, int a;, public :, void getdata()
Page 60 :
{, Cout<<”Enter value of a”<<endl:, Cin>>a;, }, Void operator – (), {, a=-a;, }, Void show(), {, Cout<< “value of a=”<<a;, }, }, Void main(), {, Opr p;, p.getdata();, p.show();, -p;, p.show();, }, Out put, Value of a=10, Value of a=-10, Q: What is an operating overloading? Explain overloading binary operator with suitable, example., , Overloading Binary Operator:, The sane mechanism can be used to overload a binary operator. To add two numbers a statement, by overloading the + operator using an operator +() function., Example:, , Class opr, {, Private:, int a;, public :, void getdata(), {, Cout<<”Enter value of a”<<endl:, Cin>>a;, }
Page 63 :
3. We cannot change the basic meaning of an operator. That is to say. We cannot redefine the, puls(+) operator to subtract one value from the other., 4. Overloaded operators follow the syntax rules of the original operators. They cannot be, overridden., 5. There are some operators that cannot be overloaded., 6. We cannot use friend function to overload certain operators., 7. Unary operators, overloaded by means of a member function, take no explicit arguments, and return no explicit values, but, those overloaded by means of a friend function, takes one, reference argument., 8. Binary operators overloaded through a member function take one explicit argument and, those which are overloaded through a friends function take two explicit arguments, 9. When using binary operators overloaded through a member function, the left hand operand, must be an object of the relevant class., 10. Binary arithmetic operator such as +,-,* and / must explicitly return value, , MCQ, 1. Which of the following operators cannot be overloaded?, a. [], b. ->, c. ?:, d. *, 2. Which of the following keyword is used to overload an operator?, a. Overload, b. Operator, c. Friend, d. Override
Page 64 :
UNIT VI, Inheritance in C++, -------------------------------------------------------Q: What is Inheritance? Explain types of inheritance., Introduction:, C++ supports the concept of reusability once a class has been written and tested, it can be, adapted by other programmers to suit their requirements. This is basically done by creating new, Classes, reusing the properties of the existing ones. The mechanism of deriving a new class from an, old one is called inheritance., The old class is referred to as base class or super class. And the new one is called as derived class or, subclass., The Inheritance is the mechanism of deriving one class from the other class. Let us assume, that the class def is derived from the existing base class abc. In that case abc is called as base class, and def is called as derived class. The feature that is facility of the base class will be inherited to the, derived class. The derived class will have its own features. The features of the derived class will, never be inherited to the base class., Defining Derived Classes:, A derived classes can be defined by specifying its relationship with the base class in addition, to its own details. The general form of defining class is :, Class derived-class-name: visibility-mode base-class-name, {, ----------------};, The colon indiactes that the derived-class-name from the base-class-name. the visibility-mode is, optional and, if present, may be either private or public. The default visibility-mode is private., Visibility mode specifies whether the feature of the base class are privately derived or publically, derived., Example :, Class ABC: private XYZ, {, Members of ABC, }:, Class ABC: public XYZ, {
Page 65 :
Members of ABC, }, Class ABC: public XYZ, {, Members of ABC, }, , TYPES OF INHERITANCE: There are five types of inheritance as follows:, 1. Single Inheritance: A derived class with only one base class, is called Single Inheritance., , 2. Multiple Inheritance: A derived class with several base classes, is called multiple Inheritance., , 3. Hierarchical Inheritance: The properties of one class may be inherited by more than one class, is called hierarchical Inheritance.
Page 66 :
Multilevel Inheritance: The mechanism of deriving a class from another derived class is known, as multilevel Inheritance, , Hybrid Inheritance: The hybrid Inheritance is a combination of all types of Inheritance., , Q: What is inheritance? Explain single inheritance with example, Single Inheritance:, A base class B and a derived class D. the class B contains one private data member, one public, data member, and three public member function. The class D contain one private data member, and two public member function., Class B, {, Protected:, int a, b;, public:, void getdata( );, {, Cout<< “Enter the value of a and b”<< endl;, Cin>>a>>b;
Page 67 :
}, }, Class D: public B, {, Protected :, int c;, public:, void show(), {, C=a+b;, Cout<< “Addition of a and b=”<<C<<endl;, }, }, Void main(), {, D d1;, d1.getdata();, d1.show();, }, Q: What is inheritance? Explain multilevel inheritance with example, Multilevel Inheritance:, A class is derived from another derived class. The class A servers as a base class for the derived, class B, which in turn serves as a base class for the derived class C. the class B is known as, intermediate base class since it provides a link for the inheritance between A and C. the chain ABC, is known as inheritance path., Example:, Class B, {, Protected:, int a;, public:, void getdata( );, {, Cout<< “Enter the value of a ”<< endl;, Cin>>a;, }, }, Class C: public B, {, Protected :, int b;
Page 68 :
public:, void getdata1( );, {, Cout<< “Enter the value of b”<< endl;, Cin>>b;, }, Class D: public C, {, Protected :, int c;, public:, void show(), {, C=a+b;, Cout<< “Addition of a and b=”<<C<<endl;, }, }, Void main(), {, D d1;, d1.getdata();, d1.getdata1();, d1.show();, }, , Q: What is inheritance? Explain multiple inheritance with example, Multiple Inheritance:, A class can inherit the attributes of two or more classes as shown in figure, this is known as, multiple inheritance. It allows us to combine the feature of several existing classes as a string point, for defining new classes. It is like a child inheriting the feature of several existing classes as a starting, point for defining new classes. It is like a child inheriting the physical feature of one parent of one, parent and the intelligence of another., Example:, Class B, {, Protected:, int a;, public:, void getdata( );, {, Cout<< “Enter the value of a ”<< endl;, Cin>>a;
Page 69 :
}, }, Class C, {, Protected :, int b;, public:, void getdata1( );, {, Cout<< “Enter the value of b”<< endl;, Cin>>b;, }, Class D: public B, public C, {, Protected :, int c;, public:, void show(), {, C=a+b;, Cout<< “Addition of a and b=”<<C<<endl;, }, }, Void main(), {, D d1;, d1.getdata();, d1.getdata1();, d1.show();, }, , Q: What is inheritance? Explain Hierarchical inheritance with example, Hierarchical inheritance:, Inheritance can be used to modify a class when it did not satisfy the requirements of a, particular problem on hand. Additional members are added through inheritance to extend the, capabilities of class. Another interesting application of inheritance is to use it as a support to the, hierarchical design of a problem. Many programming problems can be cast into a hierarchy where, certain feature of one level are shared by many others below that level., Class B, {, Protected:, int a,b;, public:
Page 71 :
Hybrid inheritance is a combination any type of inheritance i.e. single, multilevel, multiple,, hierarchical inheritance., Example:, Class A, {, Protected:, int a,b;, public:, void getdata( );, {, Cout<< “Enter the value of a and b ”<< endl;, Cin>>a>>b;, }, }, Class B: public A, {, Protected :, int c;, public:, void show(), {, C=a+b;, Cout<< “Addition of a and b=”<<C<<endl;, }, Class C: public A, {, Protected :, int c;, public:, void show1(), {, C=a*b;, Cout<< “Multiplication of a and b=”<<C<<endl;, }, }, Class D: public B, public C, {, Protected :, int c;, public:, void show2(), {, C=a-b;
Page 72 :
Cout<< “Subtraction of a and b=”<<C<<endl;, }, }, Void main(), {, D d1;, d1.getdata();, d1.show();, d1.show1();, d1.show2();, }, , Q: Explain virtual base class in detail., Virtual Base Class, Consider a situation where all the three kinds of inheritance, namely, multilevel, multiple and, hierarchical instances are involved. Consider the following example illustrated in a figure., , The D has two direct base classes B and C which themselves have a common base class, ‘school’. The D inherits the traits of ‘A’ via two separate paths. It can also inherit directly as shown, by the broken line. The ‘A’ is sometimes referred to as indirect base class. All the public and, protected members of ‘A’ are inherited into ‘D’ twice, first via ‘B’ and again via ‘C’.This means, ‘D’, would have duplicate sets of the members inherited from ‘A’. This introduces ambiguity and should, be avoided., Example:, Class A, {, Protected:, int a,b;, public:, void getdata( );, {
Page 73 :
Cout<< “Enter the value of a and b ”<< endl;, Cin>>a>>b;, }, }, Class B: virtual public A, {, Protected :, int c;, public:, void show(), {, C=a+b;, Cout<< “Addition of a and b=”<<C<<endl;, }, Class C: public virtual A, {, Protected :, int c;, public:, void show1(), {, C=a*b;, Cout<< “Multiplication of a and b=”<<C<<endl;, }, }, Class D: public B, public C, {, Protected :, int c;, public:, void show2(), {, C=a-b;, Cout<< “Subtraction of a and b=”<<C<<endl;, }, }, Void main(), {, D d1;, d1.getdata();, d1.show();, d1.show1();
Page 74 :
d1.show2();, }, Q; Write a short notes on abstract class., Abstract Classes:, An abstract class is one that is not used to create objects. An abstract class is designed only to act as, a base class. It is design concept in program development and provides a base upon which other, classes may be built. In the previous example, the student class is an abstract class since it was not, used create any objects, , MCQ, 1. Which of the following are available only in the class hierarchy chain?, a. Public data members, b. Private data members, c. Protected data members, d. Member functions, 2. Which of the following is not a type of inheritance?, a. Multiple, b. Multilevel, c. Distributive, d. Hierarchical, 3. Which one of the following is the correct way to declare a pure virtual function?, a. virtual void Display(void){0};, b. virtual void Display = 0;, c. virtual void Display(void) = 0;, d. void Display(void) = 0;, 4. Which of the following is an invalid visibility label while inheriting a class?, a. Public, b. Private, c. Protected, d. Friend, 5. Which of the following is used to make an abstract class?, a. Declaring it abstract using static keyword., b. Declaring it abstract using virtual keyword., c. Making at least one member function as virtual function., d. Making at least one member function as pure virtual function., , //////////////////////// BEST OF LUCK\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\