0% found this document useful (0 votes)
8 views26 pages

C++ Unit - 1

The document discusses the principles of Object Oriented Programming (OOP) and contrasts it with Procedure Oriented Programming (POP). It outlines key concepts of OOP such as objects, classes, data abstraction, encapsulation, inheritance, polymorphism, and dynamic binding, emphasizing the advantages of OOP like simplicity, modularity, and reusability. Additionally, it touches on the basics of C++ programming, including tokens, keywords, identifiers, constants, and user-defined data types.

Uploaded by

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

C++ Unit - 1

The document discusses the principles of Object Oriented Programming (OOP) and contrasts it with Procedure Oriented Programming (POP). It outlines key concepts of OOP such as objects, classes, data abstraction, encapsulation, inheritance, polymorphism, and dynamic binding, emphasizing the advantages of OOP like simplicity, modularity, and reusability. Additionally, it touches on the basics of C++ programming, including tokens, keywords, identifiers, constants, and user-defined data types.

Uploaded by

jaynthir01
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 26
Chapter-1 Principles of Object Oriented Programming 1.1 Object Oriented Programming (OOP) Object oriented programming is known as OOPs. Obj&ct oriented Programming is an approach that provides a way of modularizing programs by creating partitioned memory area for both data and functions that can be used as templates for creating copies of such modules on demand. (i.e. OOP allows us to decompose a problem into a number of entities called objects and then builds data and functions around these entities). 1.2 Procedure Oriented Programming (POP) The given problem is divided into a number of sub problems depending upon its functionality. The sub problems are called procedures or Methods. Any procedure can be called at any point during the program execution. © The program has global and local-variables. _ on * _ Global variables can be only be used : Global data Blain progam Local data a a Local Data Local Dat ‘Local Data | Function-4 ‘Function-5 Local Data ‘Local Data 1.2.1 Features of procedure oriented Programming: Large Programs are divided into small function or procedure. Uses Top-Down programming Approach. Data moves freely from one function to another. Most of the finctions share common data. Emphasis is given for algorithms. 4 Dt 122 Tiflerene betwen Precetere Oriented Programming "ny oeterrtet P ongermmereerting, 2 4 Ot Pence Oriented Object Oriented Progra, _ preening } miming >| Fenris te om desing things | Penphasis is on data tithes —| (aigrritme ) | ‘han | "Lange Programe are divided into | Programs are divided into objec 8 Data hiding and moving is possibi Object can exchange data through its fonetl functions 1 ses wp-Gown programming | It uses bottoni-tip programs vechmour technique. It is easy to add new data and functions 1.3 Object Oriented Programming Paradigm ‘The Program is divided into number of small units called Object. The date and function are built around these objects. The data of the objects cari be accessed onily by the functions associate with that object. The functions of one object can access the functions of other object. Principles of Object Oriented Programming 13 oe Features of Object Oriented Programming ¢ Emphasis is given on data rather than procedures. ¢ Problems are divided into objects. Data structures are designed such that they organize the object. ¢ Data and function are tied together. © Data hiding is possible. © New data and functions can be easily loaded. ¢ Object can communicate with each other using functidns. © Bottom-up programming approach is used. 1,5 Basic Concepts of OOPs ¢ key basic concepts of object oriented programming are as follows: Objects Classes 202000000 1.5.1 Objects —= f ( ‘ Object is the basic unit of object-oriented Programming. Objects are identified by its unique name, An object represents a particular instance of a class. There can be more than one instance of an object. Each instance of an object can hold its own relevant data, An Object is a collection of data members and associated member functions also known as methods. 1.5.2 Classes Classes are data types based on which objects’ are created. Objects with similar properties and methods are grouped together to form a Class. Thus, a Class ‘represents a set of individual objects. Characteristics of an object are represented in a class as Properties (Attributes). The actions that can be performed by objects become functions of the class and are referred to as For example, consider we have a Class of Cars under which Santro Xing, Alto and Wagan, R represents individual Objects. In this context each Car Object will have its own, Model, Year of Manufacture, Colour, Top Speed, Engine Power Cte., which form Properties of the Car class and the associated actions ie, object functions like Start, Move, Stop form the Methods of Car Class. i =) Aw. tu z a —_—— ma Programming in C++ and Data Structure 1.5.3 Data Abstraction Reb aa dulacll 06> ; The technique of creating new d: types that is Canal application to be programmed. It provides the ability to create user-defined data types, for modeling a real world object, having the properties of built-in data types and a set of permitted operators. 1.5.4 Encapsulation A mechanism that associates the code and the data it manipulates into a , pe en en ee ey ek hepry 13s Gene chim inte a Snghe unib 15 It allows the extension and reuse of existing code without having to rewrite the code from scratch. Inheritance involves the creation of new classes (derived classes) from the existing ones (base classes), thus enabling the creation of a hierarchy of classes that stimulate the class and subclass concept of the real world. The new derived class inherits the members of the base class and also adds its own. 1.5.6 Polymorphism Polymorphism (from Greek meaning “many forms”) allows 2 single name/operator to be associated with different operations depending on the type of data passed to it In C++, it is achieved by function overloading, operator over loading and dynamic binding (virtual functions). 5.7 Dynamic binding Dynattiic theatis that the code associated with a given procedure call is not known until the time of the call at run-time 1.5.8 Message Passing ‘The process of invoking. an. operation on an object. In response 10 & message, the corresponding method (function) is executed in the object. Sh Benefits of OOP : itis easy to model areal system as real objects are represented by prograrran’ objects in OOP. The objects are processed by their member data and functions It is easy to analyze the user requirements. . «With the help of inheritance, we can reuse the existing class to derive ae class such that the redundant code is climinated and the use © existinig’class is extended. This saves time and cost of program. «Jn OOP, data can be madd private to a class such that only member oor ofthe clas can access the data, Ths principle of data hid helps the to build a secure program that cannot be vi by code in other part of the program. 4 ¢ With the help of polymorphism, the same function or same operator can be used for different purposes. This helps to manage softwar complexity easily. ‘ al Principles of Ohiect Oriented Programming 15 eo. problems can be reduced to smaller and more manageable Sallis Ws ey Ws parton es eek Dest toed on ont * — Itis possible to have ttiultiple instances of an object % co-exist without any interference i.e. each object has its own separate member data and function, 1.7 Advantages of OOP ‘The major advantages of OOPs are: 1. Simplicity Software objects model real world objects, so the complexity is reduced and the program structure is very clear. 2. Modularity Each object forms a separate entity whose internal workings are decoupled from other parts of the system. 3. Modifiability It is easy to make minor changes in the data representation or the procedures in an OO program. Changes insidé a class d6 not affect any other part of a program, since the only public interface that the external world has to a class is through the use of methods. 4. Extensibility Adding new features or responding to changing operating environments can be solved by introducing a few new objects and modifying some existing ones. 5. Maintainabili Objects can be maintained separately, making locating and fixing problems easier. 6. Re-usability Objects can be reused in different programs. 18 Applications of OOP / Usage of OOP * Used in Computer Animation © — Used to access Relational Databases. * Artificial intelligence and Expert Systems. * CAD/CAMICIM Systems. Used in logical networking designing, Used to Develop Expert System Software Develop Computer Games Real time Systems. Simulation and Modeling. © Neural Networks and Parallel Programming. Chapter 4 Basics of C++ 4.1 Tokens ‘Smallest individual units in a C++ program are referred to as tokens, ‘The various types of tokens are as follows: Keywords Identifiers _ Constants Operators Strings Variables 4.1.1 Keywords Keywords also referred as reserved words. Keywords have standard predefined specific meaning. The user has no right to change its meaning, ‘Keywords should be written in lower case. They should be written in lower. case letters. The following keywords are reserved for C++: asm auto bad_cast__| bad_typeid bool break _| case catch char class const const_cast continue | default delete do double | dynamic cast | else enum, except licit extern false finally [oe for friend [goto [if inline int long mutable namespace | new | operator | private | protected | public register | reinterpret cast | return short signed sizeof static Static_cast struct | switch template | this throw true try type_info | typedef x | typename | union unsij Usi n virtual void 4.1.2 Identifiers Identifiers are names given to variables, class, methods, objects and interface in a program, These are user defined names. Identifiers should follow the following rules: (i) They can have digits, alphabets, underscore and dollar sign character. (ii) The first character must be an alphabet (iii) They can be of any number of characters. (iv) They are case sensitive. ie. Upper case and lower case letters are different. Eg: Sum is different from sum. Table: Contains a list of valid and invalid identifiers names Valid Identifiers Invalid Identifiers A2 while (this is a java keyword) SUM .9D (uses a period operator) Sum roll no (uses a space) C18 94 (does not begin with a letter) balance_amount 3ABC.(begins with a numeral) Table: Valid and Invalid java identifiers 4.13 Constants A constant is a quantity whose value does not change during the execution of the program. There are three types of constants in C++. They are, 1. Numeric Constants 2: Character Constants 3. String Constants 1. Numeric Constants A numeric constants is a constant made up of digits and some special . There are two types of numeric constants. They are 1. Integer or fixed point constants 2, Real or floating point constants 1. Integer or Fixed Point Constants __ Integer constant is a constant made up of digits without decimal point. This can have values from — 32, 768 to +32,767. For example, 125 Programming in C++ and Data Stritin 3. String Constants . String constants is « st of characters are represented with double quote For example, “College” “school” © Basic Date type © User defined data type Derived Data Type 42.5 Basic Date — Dats Variable Type Size Range ec = " byte | -128 to 127 Tae Imeger 2bytes | -32,768 to 32,767 | Snort Short integer te [32,768 to 32,767 [Sinon int ‘Short integer Ibyte | -32,768 to 32,767 ‘Long int Long integer 4 bytes | -2,147,483,648 to I 2,147,483,648 | Unsigned char | Unsigned character | I byte | 0 to 255 Unsigued int | Unsigned int 2 bytes | 0 to 65,535 Unsigned Unsigned short | Oto 65,535 sho 0 to 4,294,967,295 340-38 to 3.40+38 Bbytes | 1.7e-308 to ; 1,76+308 L1E+4932 Double Basics of C++ 44 4.2.2 User defined data type Cae dclinnd cts pes ain dara cypes defined bry the wer The various user defined data types are as follows: e = Structure e Union e Enumeration e Class 4.2.2.1 Structure ‘A structure is a collection of variables under a single name. These variables can be of different types, and each has a name which is used to select it from the structure. A structure is a convenient way of grouping several pieces of related information together. Defining structure A structure definition contains a keyword struct and a user defined tag~ field. The general format is, struct tag-field { datatype member1; datatype member1; Struct - keyword to define structure Tag-field - name of the structure Datatype —_- valid c datatype Example Below structure can be defined for storing book details of a book store. struct book_store char title(15] char author[15]; int pages; float price; Ve This defines a structure with four members namely, title, author, pages and price of different data types. ‘The name of the structure is bool ose 4.5 Semis Sui Da tl ee Structure declaration Structure declaration means combining template declarations variable declarations. The general format is and struct tag-filed variablel, variable2,..... variablen, Example i struct book_store { char title[15]; char author[15]; int pages; float price; struct book_store, bookl,book2,book3; } Giving values to structure members fember operator or dot operator is used to establish a link between member iia structure an structure Variable.(‘.‘). The general format is structure variable . membername; Example #include void main( ) { struct book_store { int pages; float price; }book1; main() { struct book_store bookl; cout<<“Enter the no. of pages”; cin>>book. pages? cout<<” Enter the price”; cin>>book.price; cout<<”Book Store Details”; cout<<"No. of Pages="<Less RAM space is required thus fast execution of program. Disadvantage of Union over structure >If we use 2 or more instance of single onion the data will be lost after data for second instance is entered. 4.2.2.3 Enumeration Enumerations create new data types to. contain something different that is not limited to the values fundamental data types may take. The general form is enum enumeration_name { valuel, value2, value3, e object_names; For example, we could create a new type of variable called color to store colors with the following declaration: hd Programming in C++ and Data Structure enum colors{blue, green, cyan, red, purple,); We can explicitly specify an integer value for any of the constant values that our enumerated tyre car che If the constant value that follows it is not Given an integer value, it is automatically assumed the same value as the Previous one plus one. wate ; enum months{ january=1, february, march, april, may, june, july, august, september, october, november, december}; {In this case, variable y2k of enumerated type months can contain any of the 12 possible values that go from January to December and that are ‘cquivalent to values between 1 and 12 (not between 0 and 11, since we have made January equal to 1). 4224 Chass A class is @ user defined data type. The mechanism that allows you to combine datz and the function in a single unit is ‘called a class, A clase Seek ini is called objector instance. Classes are generally declared using ~ ‘the keyword class. st The data and functions in a class can be defined by any one of the fe i fiers. as { private; members}; protected: members2; Public: members3; Basics of C++ 4.10 Where class_name is a valid identifier for the class, The. body of the declaration can contain members, that can be either data or function declarations, The members of a class aré classified into, three categories: private, public, and protected, Private, protected, and public are reserved words and are called member access specifiers, 4.2.3 Derived Data Types Derived Data Types are data types derived from existing data types such as basic data types or user defined data types. They are _-® Arrays « Pointers «- Functions 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 one larger than the number of character in the string wherein c, it is exact same as the length of sting constant. Example _ char stringl[3] = “ab”; //incH+ ~ char stringl[2] = “ab”; //inc. “L | Pointers : A pointer is a variable that contains the memory location of another variable in which data is stored. Using pointer, you start by specifying the type of daia stored in the location. The asterisk helps to tell the compiler that you are creating a pointer variable. Firialiy-you have to give the name of the variable. The address operator & is used to get the address of any data object and it is stored in Pointer type data object. Example int * ip; //int pointer ip = 6x; /laddress of x through indirection .. C++ adds the concept of constant pointer & pointer to a constant pointer. Functions Functions are the building blocks of the C programming language. The most important of the C++ functions is the main () function. A function can be invoked from different parts of the main prog a An operator is a symbol which helps the user to command the computer to do a certain mathematical or logical manipulations. Operators are used in C language program to operate on’data and-variables. C has a rich set of Operators which can be classified as . in CH and Data Structure “Asithmetic are used to perform erithmetc = provides basic arithmetic operators. They ae vh a able shows you, the different Arithmetic operators that were a cH programming. Operators ali Example Meaning > atb ‘Addition (or) Unary plus - ab Subtraction (or) Unary minus * atb Multiplication 7 afb Division % a%b Modulo division (Remainder) Table Arithmetic operators 4.2.42 Relational Operators Relational operators are used to find out the relationship between tw operands. Table shows you the different relational operators used in ¢ programming. Operator | Operations | Example < Less than asb > | Greater than @b <= | Less than or| ab L equal to >= |Greater than | a>=b equal to tT —| Equal to a=b Not equal to al=> 412 4.2.4.3 Lagion! Operators i npics! opermtcr is used to find out the relationship between two or more relationship expressions. Table below shows you the different logical omeraines need in C Programming The logical operators && and | | are used when we want to form compound conditions by combining two or more relations. Logical operators return results indicated in the following table. afeafa " Logical AND (&&) ~~ This operator is used to evaluate two conditions or expressions with relational operators simultaneously. If both the expressions to the left and to the right of the logical operator is true, then the whole compound expression is true. Example a>b&&x==10 ‘The expression to the left is a > b and that on the right is x = 10 the whole expression is true only if both expressions are true i.e., if a is greater than b and x is equal to 10. Example a= 9) the NOT expression evaluates to true only if the value of x it neither greater than or equal to y 4.2.4.4 Assignment Operators Assignment operators are used to assign the value of an expression to ariable The Aseignment Operator evaluates an expression on the right of the expression and substitutes it to the value or variable om the left of th expression. The general form is V op=exp; Where, \V_ - variable ‘Exp - expression Op -C binary operators = -Js knownas the assignment operators. V op=exp; is equal to V=V op (exp); ie, xt=y+l; is equal to x=x+(y+1); “The table given below lists the assignment operators with example operato oe Operators | Meaning Expression + Add assign xXt=a X=xta = Subassign, | X=a Xj Xoca = Multiple assign | X*=a_— | X=x*a / Division xa | X-xa % Modulo X%n-a | Xextha ‘Table Assignment operators Example x=atb Here, the value of a + b is evaluated and substituted to the variable x. addition, C has a set of shorthand assignment operators of the form. 4.2.4.5 Increment and Decrement Operators C++ has two very useful operators. They are increment (+4) a0 decrement (~) operators. The increment operator (++) adds 1 to the operat satue contained in the variable. The decrement operator (-) subtract fron the valae contained in the variable. The increment and decrement opersiot Basics of C++ 414 are one of the unary operators which are very usefull in C++ language. They are extensively used in for and while loops. Increment Decrement fos fo Pre increment Post increment Pre decrement Post Decrement (+ Variable) (Variable ++) (~~ Variable) (Variable --) The increment operator ++ adds the value 1 to the current value of operand and the decrement operator - — subtracts the value 1 from the current value of operand. ++variable name and variable name++ mean the same thing when they form statements independently, they behave differently when they are used in expression on the right hand side of an assignment statement. Example Consider the following. m=5; y= ++m:; (prefix) In this case the value of y and m would be 6 Suppose if we rewrite the above statement as m=5; y = m+; (post fix) Then the value of y will be 5 and that of m will be 6. A prefix operator first adds 1 to the operand and then the result is assigned to the variable on the left. On the other hand, a postfix operator first assigns the value to the 4.2.4.6 Bitwise Operators Bitwise operators are used to perform bit by bit operations. A bitwise operator operates on each bit of data. Those operators are used for testing, complementing or shifting bits to the right on left. Bitwise operators may not be applied to a float or double. The table given below lists the various bitwise operators. 4.15 Programming in C++ and Data Structure i ee en NR tee meee > Bitwise Right Shift << | Bitwise Left Shit ~ Bitwise Complement Table Bitwise operators Bitwise AND (&) ‘The bitwise operations are carried out between two bit patterns. Example Let x=0101 y= 1011 x & y=0001 Bitwise OR(| |) ‘The bitwise operations is carried out between two bit patterns. Let x=0100 y=1011 xly= 1111 Bitwise exclusive OR(\) Let x=0010 y=1010 x y= 1000 4.2.4.7 Conditional Operator The conditional operators aré also called temary operator. They are used to construct conditional expressions. Conditional operator has three operands. The general format is: condition?expression1:expression2; If the result of condition is TRUE (non-zero), expression! is evaluated and the result of the evaluation becomes the result of the operation. If the condition is FALSE (zero), then expression2 is evaluated and its result becomes the result of the operation. For Example int x=10, y=15; int y= (x>y)?x : yz In the above example, check x>10, if is true, print x value otherwise y- 4.2.5 Scope Resolution Operator (::) Scope resolution operator is denoted by a pair of colon (::).The scope resolution operator: : is used to access global variable in the inner block. When global and local variable are identical names, the scope resolutiot operator will help to access the global variable in the inner block. The general form is classname::variable or function name Ca ent AG Example #include char c = ‘a’; 1 global variable int main() { char c = 'b'; — /Nocal variable cout << “Local c: " << c << "\n"; cout << "Global c: " << ::¢ << "\n"; —/fusing’scope resolution operator return 0; } Example 2 #include class programming { public: void output(); //function declaration Me // fanction definition outside the class void programming: :output() { cout << "Function defined outside the class.\n"; } int main() { aa programming x; x.output (); return 0; I 4.2.6 Member dereferencing operator Member dereferencing operators are operators which are used to accéss the member functions in a class through pointer. The various member dereferencing operators are as follows: : :* Pointer to member decelerator * Pointer to member operator .* Pointer to member operator 4.2.7 Memory Management Operators Memory management operators are used to change the available memory in an efficient manner. There are two types of memory management operators. They are, ° New e Delete 42.7.1 New This operator is used to allocate memory spece for any object(date type). The general form is Pointer_variable=new datatype; 4.17 Programming in C++ and Data Structure Pointer_variable= new datatype( value); Pointer_variable—=new datatype(size); Example int *p; p = new int; The sbove two statements can be written in one stroke or line. int *p = new int; *p = 25; Assigning 25 through pointer int *p = new int(25)7 427.2 Delete This operator is used to release the allocated memory by using new ‘operator. The general form is delete Pointer_type_variable; Example delete p; will release the memory stored by the pointer variable p. 428 Comma Operator ~The comma operator can be used to link related expressions together. A comma-linked list of expressions are evaluated left to right and value of right most expression is the value of the combined expression. eee value = (x= 10, y=5,x+y)s First assigns 10 to x and 5 to y and finally assigns 15 to value. Since comma has the lowest precedence in operators the parenthesis is necessary. Some examples of comma operator are in for loops: for (n=1, m=10, n <=m; n++,m++) Exchanging values. tex xy yet 4.29 sizeof operator t . This operator accepts one parameter, which can be either a type or # variable itself and returns the size in bytes of that type or object: a= sizeof (char); This will assign the value 1 to a, because char is a one-byte long type. The value returned by sizeof is a constant, so it is always determined before program execution. 4.3 Strings Variables that can store non-numerical values that are longer than single character are known as strings. The C++ language library provides ‘The following initialization formats are valid for strings: Basics of C++ 418 string mystring = “This is a string”; string mystring (“This is a string”), Example #include #include int main() { string a("abcd efg"); string b = "xyz ijk"; string c = a + b+ //concatenation cout << "First character of '"<< ¢ <<"' is : " << c[0] << endl; // as inc return 0; } 44 Variables Variable is a quantity which changes during the execution of a program. Declaration does three things. 1. It gives name to memory location. 2. It specifies the type of data. 3. It allocates memory space. Rules for naming variables «The first character in a variable name must be an alphabets, underscore( _); dollar sign($) © Commas or blanks spaces are not allowed within a variable name. * Variable names are case sensitive (i.e, regno. is different from REGNO) 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. The general format is data_type variable_name; If you are going to declare more than one variable of the same type, you can declare all of them in a single statement by separating their identifiers with commas, The general form is: datatype varl, lvar2,....varns where, datatype - any valid datatype 4.19 Programming in C++ and Data Structurs varl,var2,...varn - name of the variables Some valid variable declarations are as follows Eample int count; float x,y; double pl; Example #include /T header file for input/output stream #include / header file for standard int main( ) { int numberl, number2, number3;// declaration of variables float average; clrscr(); // Clear the output screen cout << "Enter first integer: "; cin >> numberl; cout << "Enter second integer: "; cin >> number2? cout << "Enter third integer: "; cin >> number3; average = (numberl + number2 + number3) /3.0; 1 calculates the average cout << "The average of the three integers is: "“ << average << endl; getch(); // Wait for a character expression from keyboard return 0; } 11 ead main( ) Initialization of variables The general format is: datatype variable name = value or expression/ Example : int a=10; char c=M'G String str="MAN"; Write 2 C++ program to initialize more than one variable at = time. #include se lc gg hab void main() { int a,b,c; a=10,b=15,c=20; cout<<”A="<

You might also like