C++ Programming
INTRODUCTION
Data : Marks
Name
Age
Fees
Total
Percentage
Output
Definition
C++ Standard library
{
int n = 10 ;
clrscr ( ) ;
cout << set w (10) << n;
getch ( ) ;
}
Output : 10
Private : // optional , private by default variable declaration:
Function ( ) declaration;
Public :
Variable declaration ;
function declaration;
};
Class_name object 1 , object 2,................. object N;
{ {
member 1; member 1;
member 2; member 2;
---------- ---------
---------- ---------
}; };
char A[20]; // char array
A points to B
A = &B ;
A is pointer to B
INTRODUCTION
c++ is an object oriented programming language (oops) . It was developed by AT & T Bell laboratories in the early 1980 in USA by BJARN STROUSTRUP. It is derived from the 'C' language , It is also known as expended version of 'C' language . C++ can run most the 'C' programs . It is a multi-paradigm language procedural as well as object oriented. The most important features of C++ are concerned with class , object , and object oriented programming(oops). Initially it was called by the name " C" with classes. While later in 1983 the name was changed to C++ by RICK MASCITTI. The idea of C++ comes from C increment operator ++.......... C++ support function overloading , overloading means two or more functions having the same name in the same program. This can be done only in C++ with the help of polymorphism (an opps features). In C++ , we can use function inside structure . The standard input/output function are differ in C++ language . The "cin" function is used for input and "cout" is used for output.
PROCEDURE ORIENTED PROGRAMMING : conventional programming , using high level languages such as COBOL, FORTRAN , PASCAL, AND C are known as procedural - oriented approach . The problem is solved as sequence such as reading , calculating , and printing. A number of function are written to solve this problem. It basically consist of a list of instructions for the computer . An entity that organizes these instructions into a group is known as function.
Object Oriented Programming Approach : The major objective of object - oriented approach is to remove some of the difficulties encountered in the procedural approach . Oops treats data as a critical element in the program creation and does not it to flow freely around the program. It bounds (ties) data more closely into a unit called function that acts on it and protect it from accidential modification from outside world (function) . Oops allows decomposition of a problem into objects and then build data & function around these objects . The data of an objects can be accessed only by the functions associated with that objects.Some Important Features Of Oops are
- Stress is an objects
- Programs are divide into objects .
- Objects may communicate through messages .
- Data is hidden and cannot be accessed by outside world.
- function and data are tied together into a unit (class).
- New data type & functions can be easily added.
- Objects
- Classes
- Data Abstraction
- Inheritance
- Data Encapsulation
- Polymorphism
- Modularity
- Dynamic Binding
- Message Passing
Objects : student
- Objects = Objects are the basic run - time entities in a oops language. Also Object is an entity that has a fixed shape or well defined boundary . Object are used to represent a person , a place , a bank, account or a thing that the program has to handle. For ex : Employee is an object . It's characteristics are : name , age, basic salary , date of joining , Employee_ id . It behaviours are : total salary, input , display , etc. In oop language the characteristics of an objects are represented by it's data and it's behaviours is represented by it's associated function.
Data : Marks
Name
Age
Fees
Total
Percentage
Output
The basic idea behind oop language is to combine both the data and the function that operate on that data in a single unit. such a unit is called an object.
We can access the object data only by it's function i.e by calling member function. A c++ program consists of a number of objects , that communicate with each other by call each others member function
- Class : It is a collection of objects and also known as user - defined data-type and behave like the built-in data types of a programming language . The entire set of data and code of an object can be made by a user -defined , We can create any number of objects belonging to that class . Each objects is related with the data of type class in which they are created.
For Example : If 'mobile ' has been defined as a class , the statement mobile samsung ; will create an object samsung belonging to the class 'mobile'.
- Data Abstraction : It is the process of representing essential features without including background detail or explanations . In other words, Data Abstraction is the process of defining a new data type with the principal of data hiding. This new datatype is called class . Therefore the classes are also known as abstracts data type because they use the concept data abstraction. For Ex : when we ride a bike , to ride a bike we only need to know the essential features of bike riding Ex : gear handling , use of clutch , acceleraor , brakes etc. But during ridding the bike , we do not need to know the internal details of bike like wiring, motor engine etc. we only change the gears and apply the breaks etc. The internal process is hidden form us . This is the data abstraction where we only know the essential features.
- Data Encapsulation : It is the process in which the data and function are wrapped into a single unit called class. It is an important concept of oop by which we can combine both the data and function that operate on that data in a single unit. We cannot access data from outside functions and only those function which are wrapped in the class can access it . These functions are called member function and acts as the interface between the object data and the program. This type of insulation of the data is called data hiding in oop.
- Inheritance : It is the process by which objects of one class inherits the features of another class. In other ways ,The process of deriving a new class from an old class is known as inheritance . The old class is called supper class , base class , parent class and the new class is called sub class, or derived class or child class. In oop the concept of inheritance provides the idea of reuseability . It means , we can add additional features to an existing class without modifying it . It is possible to derive a new class from an old one . The new class will have the combined features of both the classes. In inheritance the classes are linked together in a hierarchy each class (except the root class) will have the super class.
Role of inheritance in oops language
- It enables "reuseability" of program code ; It allows the addition of additional features of an existing class without modifying it.
- It is transitive (that has a direct object) in nature . If a class A inherits the properties of another class B, then all sub class of A will automatically inherits the properties of B . The properties is called transitive nature of inheritance .
- We can solve real-world problems using inheritance.
- Polymorphism : It means , one name and multiple forms . It includes the ability to use the same function / operators with different functionality or results. In other word, It is the process in which a function /operators is processed in more than one form.
Polymorphism is a greek term that means the ability to take more than one form. An operator can be shown publicly with different functionality in different place . The functionality ( behaviour) depends upon the type of data used in the operation.
Operator Overloading : For Ex : The operator (+) for the addition of two number the operation will generate a sum . If the operands are strings , then the operation would produce a third string by concatenation . The process of making an operator (+) to show publicity with different behaviours indifferent instances is known as "operator overloading".
Function Overloading : Using function overloading , we can to draw various shapes , such as rectangle , circle , triangle etc, using a single function name and different types of argument . Using a single function name draw shape () to perform different types of task is known as function overloading .
- Modularity : It is the process of dividing a program into individual components . The approach of breaking down the original problem into several independent sub-problem or modules and executing these modules in sequence is called modularity or modular technique of programming .
- Dynamic Binding : Dynamic binding (also known as late binding) means the code linked with a procedure call is not known until the time of call at run- time since dynamic link libraries(dll ) include predefined function that are linked with the application program when it is loaded dynamically ( not at the time of writting a program) with dynamic link libraries , linker does not copy the library function into the programs executable file (.exc), but the makes call to the program in the library.
- Message passing : It is the process of communication in which objects communicate with one-another by sending and receiving information in the same way as we pass message to one - another.
(*Note Message : function
Encode : to change the information into a form that a computer deal.)
The process of programming involves the following basics steps:
C++ Environment
- Creating classes that define objects and their behaviour.
- Creating objects from class definations.
- Establishing communication among objects.
C++ system normally consists at three parts :
- Program development environment : The program development process consists such as:
- Edit ( by Edition) : For typing a c++ program (source code) the editor is used , by which we can make any corrections and save the program on a secondary storage device (hard disc) . The turbo c++ and borland c++ use ". c" for c program and ".cpp" (c++) for c++ programs. Zortech c++ system uses ".cxx" while UNIX AT & T version uses ".C" (capital C) and .cc extension name. Turboo c++ provides a powerful environment called Integrated development environment (IDE) . The IDE provides an source code of the c++ programs. The window is named as NONAMEOO .CPP .
- Preprocess ( by preprocessor ) & compile ( by compiler) =We give command to compile the program ; a preprocessor program is executed automatically before the compiler translate the code. The c++ preprocessor follows the instructions called peprocessor directives . After that the compiler translate the c++ program into machine language that is also called object code.
- Link ( by linker) = In this case , the object code produced by c++ compiler is linked with object code of various libraries , function and data those are used in c++ program to produce an executable file(.exe). If the programs is compiled and linked correctly , then the executable file is produced with . exe extension name .
- Load ( by loader) = Before the execution of program , if must be placed in promary memory ( Ram). This is done by the loader, that takes the exe file from disk and transfers it to (RAM).
- Excute ( by cpu) = Finally the computer executes the program one instruction at a time , under the control of it's cpu.
Standard of c and c++ language
The important features added by the ansi /iso c++ standard committee are :
- New data type
- bool
- wchar_t
- New Operators
- Const_ cast
- Static _ cast
- Dynamic _ cast
- Reinterpret_cast
- Type id
- Namespace scope
- Operator keywords
- New keywords
- New headers
- Class implementation
- Explicit constructor
- Mutable member
The language support oops features : C++, c#, java , small talk, object pascal, turbo pascal etc. The use of any particular language depends on characteristics , standard and requirement of an application , choice and reuse of the existing programs. Now c++ has become the most successful , practical , general, -purpose oop language and is widely used in industry today.Introduction to various c++ compilers
Definition
The c++ compilers are language translators that translate high - level language to it's equivalent machine language (object code).list of c++ compilers
- Turbo c++ compilers that works under ms - dos.
- Visual c++ compiler that works under Ms.windows.
- Borland c++ compiler that works under Ms.windows.
- GNU c++ compiler that works under unix/linux os.
- Green hill c++ provides c++ native and cross compiler for 680* 0 and 8800 microprocessors.
- Guidelines c++ for Ms-dos and unix system.
- Saber c++.
- Silicon graphics c++.
- sun c++.
- Zortech c++2.1.
- Ndp c++ for dos , XENIX and SUNOS.
C++ Standard library
It is a collection of function (sub program) used to developed other programs and software . The c++ standard library function and classes can improve the program performance because they are written carefully to perform efficiently. This technique also reduce the program developed time.Prototype of main () function
( *Note : prototype :: The first model or design from which other forms will be developed )
A simple program
# include <iostream.h> // include header file
# include <conio.h> // allow program to output to the screen
int main( ) // The main function begin the execution of program
{ // begin the body of function
clrscr( ) // clear the screen
cout << " c++ is a oop language " // display message
return 0; // indicate the successfull termination of the program
getch( );
}
The execution of every c++ program start only from the main function . In c++ main() returns a value to operating function . (int type)
The prototype of main ( )
- Int main ( );
- Int main (int age , char *arg[ ] );
The parameter argc (argument count ) and argv (argument vector),respectively give the number and value of the program 's command line arguments.I/O Operator
- Output operators (<<) : In c++ language the operator (<<) is called insertion or put to operator , also this operator is called an overloaded operator. This operator directs or sends the content of variable to the object on it's left . Also it sends (directs) the string to cout that sends it to the string.
Ex : cout<<"c++ is oop language ";
cout<<" x= " << x;
Manipulators
- Input Operator (>>) : The operator >> is known as extraction or get from operator. This operator takes the value from the keyboard and assign it to the variable on it's right side . It is also an overloaded operator.
Manipulators are operator used with the insertion operator (<<) to modify the display form of data . The two main manipulator are :
- End l (end of line ) (new line) : The end l manipulator is used for a new line in the printing on console window. It's functionality is same with the '\n' character used in c language.
- Set w ( set wide) : The manipulator is used to right justified the output value of the program . for Ex :
Cout << set w(5) <<n<<end l;In this statement set wc(5) will place the five spaces before the value of n.
# include <iostream.h>void main ( )
{
int n = 10 ;
clrscr ( ) ;
cout << set w (10) << n;
getch ( ) ;
}
Output : 10
Data types
The data type is method of storing data in the memory through variable . Also the type of data that a variable can store in the memory is called the data type. Data type identifies the type of data and the operations to perform on it.
Three kinds of data types are :
- Built in type (Basic / fundamental data type) : The built - in - data type are also called primitive / basic/simple fundamental data types. The built - in - data type may have several modifiers preceding them to serve the needs o various situation . The two type modifiers are:
- Size modifier : Short , Long . Ex : short int n; long int n;
- Sign modifier : Signed , Unsigned . Ex : Signed short int n ; Unsigned long int n ;
There are three built - in - data types
- Integral Type : It is a basic integer data type , it is capable for holding integer value not fractional value .
- Char : It can store character and string type data .
" Program to print the ASCII code for a char "
void main ( )
{
Char ch ='A' ;
int n ;
clrscr ( ) ;
n = ch;
cout <<" The ASCII code for "<< ch<<"="<<n;
getch( );
}
- Float : It is a keyword , it is used to declare floating point numbers . The floating point number are also called Real numbers.
- Double : It is used to declare high precision floating point number.
- Void : It is used for empty set of values and non returning functions . Also we can say it is used to specify the return type of a function when it is not returning any value and also it indicate an empty argument list to a function.
Ex : void fact ( void)
2. User - defined type : It can allow the user to invert (create) his own data types.In other ways , A special data type that is defined by the user is called user-defined data type . Class , structure , union, and enumeration are user defined data type.
- Class : It is a user -defined data type , represents a group of similar objects . Also class binds to data and associated functions together within a class the data are called data member functions.
The syntax of declaring a class and object :
Class class _ name{
Private : // optional , private by default variable declaration:
Function ( ) declaration;
Public :
Variable declaration ;
function declaration;
};
Class_name object 1 , object 2,................. object N;
- Public : A public member function of a class can be used by other member function of the class or outside the class.
- Private : A private member function can be called only the member function and friend function of the class not by outside functions.
- Protected : The protected member function can be used by the member function of the same as well as by the member function of derived class ; but not by the main ( ) function.
- Structure : It is user - defined data type using keyword Struct . It group the variable of same or different data type into a single unit.
- Union : It is similar to a structure the data member of union share common space . The definition and syntax of union is similar to structure.
Syntax structure Syntax unionStruct name Union name
{ {
member 1; member 1;
member 2; member 2;
---------- ---------
---------- ---------
}; };
3. Derived data type : Derived data types are built (derived) from the primitive or basic data types. These data types are :
- Array : It is a collection of similar two or more memory location or cells , called array elements, these are associated with a particular symbolic name . Array is called derived from the fundamental data types (such as char , int ,float , double).
Syntax : data type Array name [size];int A[10]; // integer array
char A[20]; // char array
return type function _ name (argument_ list)
- Function : It is a set of instruction that acts on data and returns a value and contains args or not. It is a part of the program that can be called by other parts of the program. The function declaration is called function prototype, it may be in following form :
The argument list contain the name and types of the arguments that must be passed to the function. Ex:Int cube (int x) ;
int *A , B;
- Pointer : It is also a variable that hold the address of other variables. If one variable contains the address of other variables , then the first variable is said to point to the second . A pointer declaration consists of a data types , an * (asterisk) operator and the variable name. Ex :
A points to B
A = &B ;
A is pointer to B
* Program to determine the use of class with public, private , protected specifier & to find sie of member "
Class size
{
Private :
int i ;
char c ;
float f ;
double d ;
protected :
char N[10] ;
Public :
void display ( )
{
cout << "size of int data type ="<<size of (i)<<"byte"<<end l;
cout <<"size of char type ="<<size of (c)<<"byte"<<end l;
cout << "size of float ="<<size of (f)<<"byte"<<end l;
cout <<"size of double ="<<size of (d)<<"byte"<<end l;
cout << "size of string ="<<size of (n)<<"byte"<<end l;
cout <<"size of class ="<<size of (size)<<"byte"<<end l;
}
};
void main
{
size s1 ; // creating object
clrscr ( ) ;
s1.display ( ) ; // calling function
getch ( ) ;
}
Program Testing
Testing and debugging is the process of detecting and removing the errors in a program , so the program provides the accurate result.
There are four types of error in c++ language such as :
- Syntax Error : This type of error occurs when the rules of the language violates (break). The c++ compiler detects and isolates these type of errors .
- Run-time Error : Any mistake or mismatch found in the declaration of the c++ data type , an out of range of array elements, these type of error are not detected by the compiler. A c++ program can run with these type of mistakes but provides incorrect results.
- Logical Errors : These errors are related to the logic of the program execution . The compiler cannot generation this type error message , while provides incorrect result. These errors occur due to poor understanding of the problem.
- Latent Error : It is a hidden type errors. This type of errors occur only when a particular set of data is used.
C++ Characters set
A char set is a group of symbol alphabets digit , special symbols and white spaces. These are used to represent the information.
- Alphabets A to Z and a to z .
- Digits 0 to 9.
- Special Symbols +,-,*, / , = ,< , > , !,@,#,$,%,^ , & , * , ( , ) .
- Keywords : Keywords are the reserved words these are used for special purpose . All these keywords have the pre - defined meaning . The color of keywords is white . These must be written in lower case . We cannot use keywords as variable .A group of keywords used in c++ language is :- Auto , Float ,Static , asm , break ,for ,struct , catch, case , goto , switch , class, delete, char , if, typedef . const, int, union, friend, continue, long int, unsigned, new, default , register , void, operator, do , return , volatile, public, double, while, private , else, signed , throw, protected, enum , size of , virtual, this .
- Identifiers : An identifier refer to the synonym of the term 'name' . In other ways , The name of any variable , function, and array, that is decided and created by the user is know as . Identifiers rules for declaring an identifiers :-
- The first char should not be a digit . It must be start with a char (A to Z).
- We cannot take special symbols or keywords as identifiers.
- The length of an identifier must be of maximum 31 char.
- We can use underscore for space , and as a variable like int ;
Nyce
ReplyDeleteNyce
ReplyDelete