Sei sulla pagina 1di 37

C++ c++ is an object oriented programming language. Initially named with 'c with classes'.

c++ was developed by Bjarne Storustrup at AT&T Bell Laboratories in the early 80's. c++ is a superset of c. Finally the name changed to c++ in 1983. C AND C++ C 1. It is a procedural programming language or structured programming language.

2.funs of c program r standard alone that they are independent funs. 3.it supports only pratical encapsulation that is data is integrated to form a structure. 4.it supports only pointers. 5.highlight of c is pointers. C++ c++ is an object oriented programming language. Initially named with 'c with classes' 2. the funs of c++ programs r combined to form a package. 3. it supports full encapsulation thatis data & funs are integrated to form a single unit. 4. it supports pointers & reference. 5. highlight of c++ is classes & objects.disadvantage of c++ is polymorphism makes a program bit slower where as in c there is no concept of polymorphism.

C++ Data Types: Constants

String constants Numeric constantscharacter constants

Alpha numeric characters enclosed in double quotes- string constants Integer, float, unsigned , hex, octal are numeric constants Character constants char. C++ operators: C++ Arithematic Operators + * / % Addition Subtraction Multiplication Division Modulo

C++ Assignment Operators

= +=

Assign right hand side value to the left hand side Value of LHS variable will be added to the RHS and assign it back to the varible in LHS

-=

Value of LHS variable will be subtracted to the RHS and assign it back to the varible in LHS

*=

Value of LHS variable will be multiplied to the RHS and assign it back to the varible in LHS

/=

Value of LHS variable will be divided to the RHS and assign it back to the varible in LHS

%=

The reminder will be stored back to the LHS after integer division carried out between the LHS variable and the RHS variable

>>=

Right shift and assign to the LHS

<<= &= |= ~=

Left shift and assign to the LHS Bitwise AND operation and assign to the LHS Bitwise OR operation and assign to the LHS Bitwise complement and assign to the LHS

C++ Comparision And Logical Operators

Relational Operators < > <= >= Lessthan Greaterthan Lessthan or equal to Greater than or equal to

Equality Operators == !Equal to Not equal to

Logical Operators && || ! Logical AND Logical OR Not

C++ Bitwise Operators

& | ^

bitwise AND bitwise inclusive OR bitwise exclusive OR(XOR)

>> << ~

bitwise right shift bitwise left shift bitwise complement

C++ Special Operators

Unary Operators * & ! ~ ++ -type sizeof Contents of the storage fiels to which a pointor is pointing Address of a variable Negative value Negation(0 if value not equal to 0; 1 if value=0) Bitwise complement Incrementer Decrementer Forced type of conversion Size of the subsequent data type or type in byte

Ternary Operator: C++ includes ternary or conditional operator. It is called ternary because it uses three expressions. The ternary operator acts like a shorthand version of the if-else construction. exp1?exp2:exp3 comma operator: C++ uses comma operator in two ways. The first use is as a seperator in the variable declaration. And the second one is as an operator in an expression for loop.

Scope Operator: The double colon :: is used as the scope resolution operator in C++. The scoping operator is also used in a class member function definition. The scope operator can also be used to differentiate between members of base classes with identical names. New and delete operators: Memory is allocated by new operator and memory is deallocated by delete operator.

C++ Tokens

Tokens:The smallest individual units in a program are known as tokens. c++ has following tokens.

* Keywords: Keywords implement specific c++ language features. There are 48 keywords in c++. c++ contains 16 extra keywords than c.

* Identifiers:Indentifiers refers to the names of variables, functions, arrays, classes etc. created by the programmers.

* Basic datatypes: (a) User defined [structure, union, class, enumeration] (b) built-in type [int, char, void, float, double] (c) derived type [array, function, pointer]

* Operators: :: -> Scope resolution operator

::* ->*

-> pointor-to-member declaration -> pointor-to-member operator

delete -> memory release operator endl -> line feed operator new -> memory allocation operator

setw -> field width operator

C++ Keywords

16 extra keywords: class catch delete friend inline new operator private protected public template this throw try virtual

asm Preprocessors in c++

Preprocessor: Preprocessor is a program that modifies the c++ source program according to directives supplied in the program. The preprocessor does not modify this program file, but creates a new file that contains the processed version of the program. This new file is then submitted to the compiler. The preprocessor makes the program easy to understand and port it from one platform to another. Rules for defining preprocessor * All preprocessor directives begin with the # sign. * They must start in the first column and there can be no space between sign and the directive. * The preprocessor directive is not terminated by a ; * Only one preprocessor directive can occur in a line. Macros in c++ Macro: A macro is simply a substitution string that is placed in a program.

example: #define max 100 void main() { char name[max]; for(i=0;i<=max-1;i++)

--------------------------------} which is internally replaced with the following program void main() { char name[100]; for(i=0;i<=100-1;i++) --------------------------------} and subsequently compiled. Each occurance of the identifier max as a token is replaced with the string 100 that follows the identifier in the #define line. Header Files in c++

Headerfiles: A headerfile contains the definition, global variable declarations and initialization by all file in a program. Header files are not compiled seperately. The header file can be included in the program using macro definition #include command. A header file can be declared as a first line in any c++ program. Example: The header file can be declared in one of the following ways #include<iostrem.h> (or) #include "iostream.h"

Standard Functions in c++ Standard functions: Standard libraries are used to perform some predefined operations on characters, strings etc. The standard libraries are invoked using different names such as library functions, built in functions or predefined functions. Most of the c++ compilers support the following standard library facilities * operations on characters * operations on strings * mathematical operations * storage allocation procedures * input/output operations

Preprocessor directives in c++

* List out c++ preprocessor directives. #include #define #undef #if #ifdef #ifndef #else #elif #endif #line

#error Macro operators in c++

* What is meant by macro operators? The macro works on the following operators Arthematic operators conditional operator comaparision operators unary operators etc. math.h in c++

* List out various functions in math.h headerfile. abs asinl atan2l atof cabsl cosl expl floorl fmod frexpl hypot ldexp log10 modf pow ldexpl log101 modfl powl ceil cosh fabs fmodl hypotl log matherr poly pow10 polyl pow101 acos atan _atold ceill coshl fabsl frexp labs logl _matherrl acosl atanl cabs cos exp floor asin atan2

sin sqrt tanh string.h in c++

sinl sqrtl tanhl

sinh tan

sinhl tanl

strcpy strncat strchr

strcmp strrev

Sailent features of object oriented programming The following arethe key features of object oriented programming * software reusability * testability * maintainability * portability * reliability Object definition in c++

What is an object and how Objects can be defined in c++. A class is a userdefined datatype, an object is an instance of a class template.

Defining object of a class: class <user defined name> { //data //methods }; <user defined name> object-1,object-2,........object-n;

Example: class student { private: char name[20],rno; public: void getdata();

}; student s1,s2; Differences between class and object in c++

What is a class? How it is different from the object Class: A class is a user defined datatype which consists of both data members and member functions.

Object: * An object is instance of a class. * When the object is created for the particular class then only the memory will be allocated. * Unless until the ojbect is created, the class is not a valid one. * We can create number of objects to single class. * We have to use object name to access the data of the class.

Datahiding: In c++, the class construct allows to declare data and methods as public, private and protected group. The implementation details of a class can be hidden. This is done by datahiding principle. Syntactic rules for defining class in c++

What are the syntactic rules governing the definition of a class datatype. * class keyword - To define the class * open braces - which tells starting the definition of the class. * Data members and member functions can be defined in private, protected and public modes. * close braces with ; - tells the end of the definition of the class. Scope resolution operator in c++

What is scope resolution operator? How it is useful for defining data member and member function of a class?

In c++, it is permited to declare the member functions either inside the class declaration or outside the class declaration. A member function can be defined out side of the class using the scope resolution operator ::

The general syntax of the member function of a class outside of its scope is return_type class_name :: member_function(argument1,2...n)

Eg: class student { int rno; char name[20]; public: void getdata(); }; void student :: getdata() { cout<<"Enter details"; cin>>rno>>name; } Object Oriented Programming

* OOP Programming is developed in 1960's.

* OOP programming mainly based on three concepts classes, objects and methods.

* OOP also supports inheritance, polymorphism....

* Object oriented programming follows bottom-to-top approach.

Concepts on Object Oriented programming or Features of oops:

Object:Objects are basic runtime entities. Or A class is a userdefined datatype, an object is an instance of a class template.

Defining object of a class: class <user defined name> { //data //methods }; <user defined name> object-1,object-2,........object-n;

Example: class student { private: char name[20],rno; public: void getdata();

}; student s1,s2;

Class:Class is a collection of objects with similar datatype. (or) A class is a user defined datatype in which we can define both datamembers and member functions.

Syntax: class <userdefinedname> { private: data_type members implementation operations list of friend functions public: data_type members implementation operations protected: data_type operations implementation operations };

class members can be one of the following member lists: * data * functions * classes

* enumerations * bitfields * friends * data type names

example: class student { private: long int rollno; int age; char sex; float height,weight; public: void getinfo(); void putinfo(); };

Defining the object of a class: In general. a class is a user defined data type, while an object is an instance of a class template. A class provides a template, which defines the member functions and variables that are required for objects of the class type. Or When the object is created for the particular class then only the memory will be allocated.

* Unless until the object is created, the class is not a valid one. * We can create number of objects to single class. * We have to use object name to access the data of the class.

Syntax for defining object: class <userdefinedname> { private: //data //methods public: //methods protected: //data }; user_defined_name object1,object2,object3.........objectn; where object1,object2,object3...are the identical class of the user_defined_name

example: class student { private:

long int rollno; int age; char gen; float height,weight; public: void getinfo(); void putinfo(); }; student s1,s2; //s1,s2 are two objects of student class

Accessing the member of a class: A data or function member of a class construct is accessed using the .(period) operator syntax: object.data_member object.member_function

example: class student { public: long int rollno; int age; char gen; float height,weight; void putinfo();

}; void main(void) { class student s1; s1.rollno=100; s1.age=15; s1.gen='f'; s1.height=5.5f; s1.weight=50.5; s1.putinfo(); }

Data encapsulation:The wrapping up of data and functions into single unit.

Data abstraction:Refers to the act of representing essential features without including the background details and explanations. Or Focusing on essential things or hiding the unwanted datas. Inheritance:Inheritance is the process by which objects of one class acquires the properties of objects of another class.

Example: The robin is a part of the class, flying bird which is again part of the class bird. The principle behind this sort of division is that each derived class shares common characteristics with the class from which it is derived. ADVANTAGES: 1. Reusability of the code.

2. To increase the reusability of the code 3. To add some enhancements to the base class.

Bird Attributes eggs

Flying Bird attributes

Non Flying Bird Attributes

Robin Attributes

swallow attributes

penguin attributes

kiwi attributes

Concept of inheritance

Polymorphism:Ability to take more than one form. poly-many morphism-forms. Or

Polymorphism can be divided in to two types: Static polymorphism: binding is taking place in compile time. The different types of static polymorphism are function 1.overloading function: using a single function name to perform different types of tasks 2. operator overloading: the process of making the operator to exhibit different behaviours in different instances . Dynamic polymorphism:The binding that takes place at run time. The different types of polymorphism are 1. Virtual function 2. Abstract class Shape draw()

Circle object Draw(circle)

Box object Draw(box)

Triangle object Draw(triangle)

Polymorphism Here, it allowing objects having different internal structures to share the same external interface. This means that general operations may be accessed in the same manner even though specific actions associated with each operations may differ. Polymorphism is used in implementing the inheritance. Dynamic Binding:Binding refers to the linking of procedure call to the code to be executed. Dynamic binding refers given procedure call is not known until the runtime

Message Passing:set of objects communicate with eachother. 1. Creating classes that define objects and behaviour. 2. Creating objects from class definitions. 3. Establishing communication among objects.

Employee.salary (name);

Object

message

information

The object have a life cycle. It can be created and destroy. Communication with the object or among the objects is feasible as long as it is alive. Benifits of OOPS

1. It supports both structured programming and object programming 2. It gives the easiest way to datahiding by the words class, public, private. 3. Inheritance. 4. Overloading of functions and operators. 5. class templates and function templates. 6. Exception handling. 7. Constructors, destructors, friends. Applications of OOPS

1. Realtime systems. 2. Simulation and modelling. 3. Object oriented database systems. 4. Artificial Intelligance and expert systems. 5. Neural network and parallel programming. 6. CAD/CAM systems.

MUTLILEVEL INHERITANCE: It is a process of creating a new class from already(existing) derived class. Here the existing derived class is intermediate base class. newly created class is derived class.

Grand father

base class

B Father Intermediate base class

Derived class

C Derived class

MULTILPLE INHERITANCE: It is a process of creating new class from more than one base classes.

Base A

Base B

Base n

Derived C

Classes and Structures:

structures 1. By default, the members of a structure are public i.e structure variables can be accessed by any function[data hiding not possible]. 2. In structures we can declare only variables. 3. We can't inherit a structure from another structure. Classes 1. By default, the members are private i.e class variables can be accessed by only class member functions [data hiding is possible]. 2. In classes we can declare both data members and member Functions. 3. We can inherit a class from another class.

What do you mean by inline function? when inline fn is called substitutiontakes place.f1 is inline fn all the stnts of f1 are substituted whereever f1 is called.inline is a referred word.advantage is execution becomes fast & there is no inline fun at runtime. inline void f1() { cout<<"hyd";cout<<"sec";cout<<"cyb";}main(){f1();}

What is function overloading and operator overloading? when same fn performs different operation,it is known as fn overloading.add(10,20)is 30add("10","20")is1000 is function overloading.

Access specifiers in c++ : Public: Class members having this specifier are accessible from objects created outside the class Protected: These members will be accessible from inside the class and its derived classes. Private: These members will be available from inside the current class only. Functions in C++ Function: A complex problem may be decomposed into a small or easily manageable parts or modules called functions. Functions are very useful to read, write, debug and modify complex programs They can also be incorporated in the main program. The main() itself is a function is invoking the other functions to perfom various tasks.

Defining a function: syntax: functiontype functionname(datatype arg1,datatype arg2....)

{ ----------------------}

calling function and called functions: calling function:The function which calls another function is known as calling function. called function:The function which is called is known as called function.

Control Statements in C++ : Conditional Expressions: if statement, if else statement, switch statement Loop Statements : for loop, while loop, do while loop Breaking control statements : break statement, continue statement, go to statement.

Conditional Expressions: if statement: The if statement is used to write conditional expressions. If the given condition is true then it will execute the statements. Otherwise it will execute optional statements. syntax: if<conditon> { --------}

example: if(age==18) { cout<<"eligible to vote"; } If else statement: In if-else statement, if the given condition is true then it will execute the statements otherwise it executes the else part statments. syntax: if<conditon> { --------} else { --------} example: if(age==18) { cout<<"eligible to vote"; }

else { cout<"Not eligible to vote"; } Switch statement:The switch statement is a special multiway decision maker that tests whether an expression matches one of the number of constants values and the braces accordingly. syntax: switch(expression) { case constant_1: { ----} break; case constant_2: { ----} break; case constant_n: { ----}

break; default: statement; } example: switch(ch) { case 'R': cout<<"Red"; break; case 'W': cout<<"White"; break; default: cout<<"Wrong choice:"; } Loop statements: For loop statement:

The for loop is most commonly used statement in c++. This loop consists of three expressions. The first expression is used to initialize the index value, the second to check whether or not the loop is to be continued again and the third to change the index value for the further iteration. syntax:

for(expression_1;expression_2;expression_3) statements; example: sum=0; for(i=0;i<=10;i++) sum=sum+i; while loop: The while loop is used when we are not certain that the loop will be executed. After checking the initial condition is true or false and finding it to be true, only then the while loop will enter into the loop operations.

syntax: while(condition) { statements; } example: sum=0; i=0; while(i<=100) { sum=sum+i; i++; }

Do while: Whenever one is certain about a test condition, then the do-while loop can be used. As it enters into loop atleast once and checks whether the given condition is true or false. As long as the test condition is true, the loop operations are repeated until the condition satisfied. syntax: do { statements; }while(condition); example: sum=0; i=0; do { sum=sum+i; i++; }while(i<=100); Breaking control statements: Break statement:

The break statement is used to terminate the control from the loop. The break statement is normally used in switch-case structre and it can be used in other loops also like for, while and do-while. syntax:

break; example1: switch(day) { case 1: cout<<"Monday"; break; --------------} example2: i=0; while(i<=10) { cout<"enter a number"; cin>>no; if(value<=0) cout<<"Zero or non -ve found"; break; } Continue statement: The continue statement is used to repeat the same operations once again even it checks the error. syntax: continue; example:

i=0; while(i<=10) { cout<"enter a number"; cin>>no; if(value<=0) cout<<"Zero or non -ve found"; continue; } Go to statement: The goto statement is used to alter the program execution sequence by transfering the control to some other part of the program. syntax: goto <name> example: goto xyz; xyz: statements;

Parameters vs Arguments

Up until now, we have not differentiated between function parameters and arguments. In common usage, the terms parameter and argument are often interchanged. However, for the purposes of further discussion, we will make a distinction between the two:

A function parameter is a variable declared in the prototype or declaration of a function:

1 void foo(int x); // prototype -- x is a parameter 2

3 void foo(int x) // declaration -- x is a parameter 4 { 5 } An argument is the value that is passed to the function in place of a parameter:

1 foo(6); // 6 is the argument passed to parameter x 2 foo(y+1); // the value of y+1 is the argument passed to parameter x When a function is called, all of the parameters of the function are created as variables, and the value of the arguments are copied into the parameters. For example:

1 void foo(int x, int y) 2

{ 3 } 4

5 foo(6, 7); When foo() is called with arguments 6 and 7, foo s parameter x is created and assigned the value of 6, and foo s parameter y is created and assigned the value of 7.

Even though parameters are not declared inside the function block, function parameters have local scope. This means that they are created when the function is invoked, and are destroyed when the function block terminates:

1 void foo(int x, int y) // x and y are created here 2 { 3 } // x and y are destroyed here There are 3 primary methods of passing arguments to functions: pass by value, pass by reference, and pass by address. The following sections will address each of those cases individually. Member functions: if a function is accessig atleast one private no, it is know as member fun. 2.if no-private nos are accessed,it is non member function.

3.member function belong to class,but not non member function it does not belong to any class. 4.member fn must be called with respect to object but not non member function. obj.fn();syntax it can access private members,but not non member function. it can be defined inside areoutside class. Cin and Cout : c-in is an object of type i-strem,c-out is an object of o-stream.

Note: still left concepts pass by value, passby ref, passby address.

Potrebbero piacerti anche