Escolar Documentos
Profissional Documentos
Cultura Documentos
What is C++ ?
Object oriented programming languages. Initially named as C with classes. C++ was developed at AT & T Bell Labs. C++ is superset of C. Three important facilities are added onto C. Classes functions overloading operator overloading C++ also allows us to create hierarchy related objects. All C programs are also C++ programs with few differences.
Input / Output
# include <iostream.h> <iostream.h> contains declaration of objects used in input/output statements (Naming conventions of header files may vary such as iostream.hpp. cin and cout are predefined objects in <iostream.h> for single interface . cin >> number is an input statement and causes program to wait for user to type in a number. The identifier cin is a predefined object in C++ that corresponds to the standard input stream (keyboard). >> is known as extraction or get from operator that extracts or gets value from keyboard. This corresponds to scanf( ) . The statement cout << number causes program to put the value of number on standard output stream (screen in this case). The operator << is called put to operator. Operators << , >> are also called bit wise operators. printf ( ) and scanf ( ) can still be used but include header file <stdio.h> .
Comments
In C /* comments */ In C ++ /* comments for multiple lines */ // single comment line and cant be inserted within the text of a rogram.
User Defined DT
struct and union are same as in C used for defining static and dynamic records. enumerated Data Type differ slightly in C++ enum shape {circle, square, triangle}; Here circle =0, square =1 and triangle =2 are automatically assigned. Here shape becomes new type name and can be used to declare new variables such as shape ellipse; More examples: enum color {red, blue=4, green=8}; enum color {red, blue=1, green=2}. Here red = 0 enum color {red=5, blues=6, green=7}; enum {off, on} {without name}. We can declare int switch1=off; int switch2=on;
Variable declaration
In C, all variables are declared { e.g., int x, y; float p, q;} at the beginning of the scope. In C++, the declaration of a variable can be anywhere in the scope but before the first use. It makes program easier to understand. Only disadvantage is that we cant see all variables at a glance used in the scope. Additional feature of C++ is dynamic or run time initialization {e.g., int x =3}.
Constants
C++ constants are to be initialized as: const int size =10; char name[size]; In C, the primitive #define is used to create constants. enum { X, Y, Z}; defines X, Y, Z as integer constants with values 0,1,2 respectively and is equivalent to defining const X = 0; const Y = 1; const Z = 2; enum { X=10, Y=20, Z=15}; is equivalent to defining const X = 10; const Y = 20; const Z = 15; Only integer constants can be defined using enum data type.
Pointers
Available in C & C++ int *i; i = & x; *i = 50; // /* address of x is assigned to i 50 value assigned to a location pointed out by i through indirection. */
Reference variables
C++ introduces a new kind of variable called reference variable which provides an alias for previously defined variable. General format is data_type &ref_var = var_name
float total = 50; float &sum = total; cout << sum; sum and total both are same locations. Major application is in passing arguments to functions [call by reference] void func1 (int &x) { x = x + 10; } main ( ) { int m = 10; f (m); } Declaration of variable in an inner block hides a declaration of the same variable in an outer block. Here :: is a scope resolution operator. { int x = 10; // x is a global variable { int x =1; // x is a local variable :: x = :: x +1; // ::x refers to global variable }; }
int *p = new int [3]; or int *p; p = new int[3]; creates memory space for an array of 3 integers where *p refers to first element, *(p+1) refers to 2nd element, and *(p+2) refers to 3rd element. int *p[3]; an array of pointers pointing to locations having integer values. Memory is allocated by using *p = new int; and elements are referenced as *p[0], *p[1] and *p[2]. delete p or delete [] p. In case of insufficient memory, new returns null pointer Advantages over malloc( ) Automatically computes the size of data Object possible to initialize object while creating memory space these can be overloaded
Functions in C++
The function int main ( ) returns a value of type int to the operating system. Here int is optional as it takes type by default. If int is specified before main ( ) then return statement is used for termination. Normal convention is that if 0 is returned then the program ran successfully while non zero value means that there is some problem.
Function prototyping must be given in C++ which gives compiler the details such as number, type of arguments and return type { e.g., float volume (int, float, float)}. Should preceed a function definition and no need to specify arguments but types are sufficient. In C++, function without arguments can be written as o void display ( ); or void display (void); However in C, ( ) means any number of arguments. In C++ this can be written (open parameter list) such as void do-something ()
Call by reference
In C, parameters are passed by value but in C++, they can be passed as reference or value. Swapping of two integer values C function void swap (int *a, int *b) { int t; t = *a; *a = *b; *b = t; } Call : swap(&m,&n) C++ function void swap (int &a, int &b) { int t; t = a; a = b; b = t; } Call : swap(m, n) Each argument in function must be declared independently inside the parenthesis.
Returning a reference
A function can also return a reference int &max (int &x, int &y); { if (x > y) return x; else return y; } Call max (a, b) returns a reference to either a or b depending upon the values. This implies that function call can appear on L.H.S in contrast to other programming Languages including such as max ( a, b ) = -1 which assigns -1 to a if a > b else 1 to b.
Default Arguments
C++ allows a call of function without specifying all its arguments. In such cases default values are specified when function is declared. Default values are always specified from right to left. float amount (float p, int t = 3, float r = 0.15); various calls :value = amount (5000, 7, .12); value = amount (5000, 7) . Here r=0.15 is taken. value = amount (5000); here t = 3 and r = 0 .15
Function Overloading
Same function name can be used to create variety of tasks . It is called function polymorphism in OOP (Object Oriented Programming) Various declarations: int add (int, int); int add (int, int, int);double add (double, double); double add (int, double); double add (double, int); Various calls: x = add(5,10); x = add(5,10,15); x = add(2.5,10.2); x = add(5,10.9); x = add(5.5,10); Compiler tries to find exact match where types of actual arguments match.
If exact match is not found then it performs internal conversions such as char int; float long ; int float; float int etc. For multiple matches error message is generated such as if we have long sq (long x); double sq (double x); function call sq (10) matches with long and double both, so error message is generated To avoid such situation, sq( ) should be used
Inline function
Ordinary function are compiled separately and called as and when required . In order to save time/overheads in calling function & returning to called program, a powerful facility is available in C++ Inline function is defined as inline int sq (int x) {return (x *x) } and call to this function is same as ordinary function i.e., p = sq (2) Inline function are not called at execution time instead function call is expanded by the body of function. In C, similar effect is achieved by macro definition defined by primitive # define. Here macro processor performs textual substitution shown below: # define rate 1.5 # define tax(x) x * rate; Macro call tax(p + 2) is expanded as {p + 2 * rate} which is not the intention. Macro cant have local variables and it does not even define a block. Macro also do not permit parameter checking. C++ solves the drawbacks of C macro with inline function which is small function of one or two lines. Inline modifier lets compiler mark a particular function to be expended rather than compiled. C++ compiler may ignore your request if your function is too long. Advantage of inline function is that they can help you write well-designed, modular programs that remain efficient at the code level. Definition is given as follows: #define rate 1.5 inline float tax (x) { return (x * rate ) }; Call to this inline function is y = tax(p + 2) which does the intended job incontrast to macro call. Speed benefits of inline functions diminish as the function grows in size
Class
class class_name { private: optional variable_declarations; function_declarations; public: variable_declarations; function_declarations; } Here variables are data members and functions are member functions. Usually grouped under two sections Private & Public. Private members can be accessed only within the class (data hiding) and not visible / accessible outside the class. Public members can be accessed from outside the class also. Only member functions (private/public) can have access to the private members (data & functions). Binding of data and functions together into a single class_type variable is called Encapsulation. For example: class item { private: int num i ; float cost ; public: get_data (int a, float b); void put data(void) } General convention for class is to make the value (variable members) part of the data type private and make the functions public. Actual function definitions can appear within the class or outside the class, anywhere in the program (valid for public functions). Objects can be created by simple declaration similar to variable: item x,y,z;
Outside the class : return_type class_name :: fun_name (arg list dec) { body } Class_name tells compiler that fun-name belongs to which class class item { int num; float cost; public: void gdata (int a, float b); void putdata (void); } void item :: gdata (int a, float b) can access private data { num = a; cost = b; }; void item :: putdata (void) { cout << num << \n; cout << cost << \n; } Making an outside function inline
Good practice is to define the member functions outside the class. We can also define such functions as inline by just using qualifier inline. class item { int num; float cost; public: void getdata (int a, float b); }; inline void item :: getdata (int a, float b) { num = a; cost = b; } Accessing class members item x; x.gdata (10,7.5); x.putdata ( ) ; // x.num = 10 is illegal Object of a class can call member function or member variables if declared in public section by using dot operator as x.gdata (10,7.5). Note that objects communicate by sending & receiving messages through the member functions. Nesting of member functions Member function can be called by using its name inside another member function of the same class. This is called nesting of member function. Private member function Some situation may require to hide member functions also. For example, deletion of account in customer file, providing increment. class sample { int m; void get (void) {....}; public: void update (void); } void sample :: update (void) { get ( ) } is legal as public function can access private function/data.
int num; public : void getdata (int a ){ num = a; count ++; } void getcount (void ) { cout << count:; cout << count << \n; } } int item :: count; // count of item is defined main ( ) { item a, b, c; a.getdata (10); b.getdata (20); c.getdata (30); a.getcount(); } Output of above program: count:3
Arrays of objects
item a[10]; a[i] . getdata; a[i] . getcount;
Returning objects
Functions can return objects. class complex { float x; float y; public : void inputdata (float r , float i) { x = r; y = i; } void show (complex c) { cout << c.x << +i << c.y << \n; } complex sum (complex c1, complex c2) { complex c3; c3.x = c1.x + c2.x; c3.y = c1.y + c2.y; return (c3); } }
main ( ) { complex a, b, c; a . inputdata (3.1, 2.1); b . inputdata (2.8, 3.4); c = sum (a, b) ; cout << c . show ( c) ; }
Pointers to Members
Address of a member (data / function) can be obtained by applying symbol & to a fully qualified class member name. A class using pointer can be declared using the operator ::* with the class name. class item { int m; public : void show ( ) ; } Pointer to the members of a class item is defined by item ::* Pointer ptr to member m is defined as int item ::* ptr = &item :: m; Here &item :: m means address of m (m is member of class item ). The pointer ptr defined above can be used to access the member m inside the member functions and not allowed to access outside the class. cout << t .* ptr Or cout << t . m are same. Here t is an object inside a member function. * is used to access a member when we use pointers to both the object and the member. ip = &t; cout << ip * ptr; // displays m .* is used when the object itself is used with the member pointer t .*ptr Note that *ptr is used like a member name
Dereferencing
10
11
Keywords may appear in any order and in any number of times in the class
Multiple inheritance
Abstract class
An abstract class is one that is not used to create objects. It can act as a base class to other classes and thus a design concept in program development that provides a base class upon which other classes may be built. Virtual class is taken as abstract class.
12
Nesting of classes
C++ supports another way of inheriting properties of one class into another. Object can be a collection of many other objects i.e., class can contain objects of other classes as its members. class alpha { }; class beta { } ; class gamma { alpha a ; beta b ; . } gamma p ; p is an object of gamma type which contains objects a and b . This relationship is called containership or nesting
Friendly functions
Non member function can not access private data of a class. If two classes A and B want to share a particular function say C to operate on the objects of both these classes, then C++ allows the common function made friendly to both the classes, there by allowing the function to have access to the private data of these classes. Such a function need not be a member of any of these classes. Declare such function as a friend of the classes such as friend void C (void) defined elsewhere in the program like a normal C++ function. function definition does not use either the keyboard friend and the scope operator :: class abc ; forward declaration. It is defined later class xyz { int x ; public : void set_value (int i) { x = i } friend void max (xyz, abc) ; }; class abc { int a ; It is defined later public : void set_value (int i) { a = i } friend void max (xyz, abc) ; }; // Definition of friend function max outside the classes void max (xyz p, abc q) { if (p.x >= q . a) cout << p.x ; else cout<< q.a } main ( ) { abc m; m . set_value (10); xyz n; n . set_value (20); max ( m, n ); No need to use scope operator :: }
13
Usually arguments of such functions are objects. A member function of any class can be friend of other class class A { int fun ( ); . } class B { friend int A :: fun ( ) ; } We can also declare all member functions of a one class as the friend functions of another class. In such cases a class is called friend class. class A { friend class B ; } Friend functions are often used in operator overloading.
Operator Overloading
Exciting feature which enhances the power of C++. Operators for built in data type can be overloaded to do the operations on variables of userdefined types. Redefine operator + to concate character strings. string s1 [10] = abc; string s2 [ 10 ] = def ; string s3 [ 20 ] ; s3 = s1 + s2 ; The semantics of operator can be extended but we can not change its syntax. The general form of the definition if defined outside the class body: return_type class_name :: operator op (list ) { ..... } return_type: type of value returned by the specified operation operator : keyword to be specified before an operator op : operator being overloaded. Operator op becomes a function name. Operator functions must be either member functions or friend functions. class complex { double real, imag ; public: constructor1 complex ( ) { } ; constructor2 complex(double x, double y ) { real = x , imag = y } declaration complex operator+ (complex c); } //end of class complex definition of complex complex :: operator + ( complex c ) operator + { complex temp; return type temp . real = real + c . real ; temp . imag = imag + c . imag return temp ; class name }
void main ( ) { complex p, q, sum ; p = complex ( 2.0, 3.5 ) ; q = complex ( 2.5, 3.5 ); sum = p + q ; }
14
It is possible to have more than one definition for any operator. String operator+ ( string ) ; Vector operator+ ( vector ) ; Matrix operator + ( matrix ) ; Simply means one name - multiple forms. Important feature of OOP. Concept is implemented using overloaded functions of operators to some extent. It is of two types : Compile time Run time Function Overloading Operator overloading Virtual functions Compile time polymorphism o Compiler selects appropriate function/operator at compilation time. o Known as early binding / static binding / static linking. Here object is bound to its function call at compile time. class A { int x; public: void show ( ) { } }; class B : public A { int y; public: void show ( ) { . } }; How to use member function show ( ) to print the values of both classes A and B ? o Since show ( ) is the same in both the places, the function is not overloaded and therefore, static binding does not apply. o Compiler in such cases defers the decision. o It would be nice if the appropriate member function could be selected while the program is running . Run time polymorphism. o C ++ supports a mechanism known as virtual function to achieve run time polymorphism. o At run time, when it is known what class objects are under consideration, the appropriate version of the function is called . o This process is called late binding /dynamic binding. It is a powerful feature of C++. o This requires the use of pointers to objects. Object pointers of virtual functions are used to implement dynamic binding ?
Polymorphism
Pointers to objects
o o o Pointer can point to an object created by a class and are useful in creating objects at run time such as item *ptr ; Here item is a class with two public functions, say, void get_data ( int a, float b) and void show ( void ). Object pointer can access the public members ( data / function ) of an object. Assume the following declarations: item x ; item *ptr = &x; Possible ways of accessing members of an object x. ptr get_data ( 100, 20.5 ) ; ptr show ( ) ; x . get_data ( 100, 20.5 ); x.show ( ) ; (*ptr) . get_data ( 100, 20.5 ) ; (*ptr) . show ( ) ;
15
Objects using pointers are created using new operator as item *ptr = new item; It allocates enough memory for the data members in the object structure and assigns the address of that space to pointer. o The pointer ptr can be used to refer to the members as ptr show ( ). o If a class has a constructor with arguments and does not include an empty constructor, then we should supply arguments when objects are created: item *ptr = new item(10,20). o We can also create an array of objects using pointer item *ptr = new item [10] ; o Here if the class contains constructors, it must also contain an empty constructor. o o
Pointers to Derived classes o pointer defined for base object can also be used for objects of derived class. (because
of type compatibility ). Base-class * ptr, b; Derived_class d ; ptr = &b ; ptr = &d valid Using ptr , we can only access those members which are inherited from Base_class.. If a member of Derived_class has the same name as in Base_class, then ptr will always access the base_class member.
Virtual Functions
Virtual functions are created for implementing late binding. Same function name can be used in both base and derived classes. We have already seen that pointer to base class always executes the functions (same name in base and derived class ) of the base class even if it is redefined in derived class. If function in base class is declared as virtual, then call to derived function is possible. class Base { public: void display ( ) { cout << Display Base ;} virtual void show ( ) {.} : }; class Derived : public Base { public: void display ( ) { cout << Display Derived ;} void show ( ) { } ; : };
main ( ) { Base B ; Derived D; Base * bptr ; bptr = &B ; bptr display ( ); bptr show ( ); // These are calls to base functions ( static binding) bptr = &D ; bptr display ( ); bptr show ( ) ; // These are calls to derived functions (dynamic binding) } When a function is made virtual, C++ determines which function to use at run time based on the type of object pointed to by the base pointer. Thus by making the base pointer to point to different objects of derived classes, we can execute different versions of the virtual function. Note that we must access virtual functions through the use of a pointer declared to the base class.
16
this pointer
C++ uses a unique keyword called this to represent an object that invokes a member function. this is a pointer that points to the object for which this function was called. Call to function max, A. max ( ) sets this pointer to the address of an object A. The starting address is the same as the address of the first variable in the class structure. The pointer this acts as an implicit argument to all the member functions. class ABC { int a ; . }
Use of private variable a inside a member function like a = 123 is same as this a = 123 ; We have not used this explicitly so far . Important application of this pointer is to return the object it points to. class person { char name [20] ; float age ; public: person( ) {}; constructor person ( char * s, float a ){ strcpy ( name, s ) ; age = a ;} person &greater ( person &x ) {if ( x . age) > = age ) return x; else return this } void display ( void ) { cout << name << age << } } main ( ) { person p1 (dam , 20.5 ), p2 ( shyam , 29.0 ), p ; p = p1 . greater ( p2 ) ; p . display ( ); //displays elder person }
17
These functions cant be used to initialize the member variables at the time of creation of their objects automatically. If the class (user defined data type) should behave similar to built-in-type, we should be able to initialize objects (class type variable) when they are declared and should be destroyed when go out of scope.
Parameterized constructors
class item { int x; int y; public : item(int a, int b ) { x = a; y = b } Now declaration item p will not work
parameterized constructor }
Two ways of object declaration using constructors: item p = item ( 2, 3 ) ; explicit call item p ( 2,3 ); implicit call Parameters of constructor can be of any type except that of the class to which it belongs. item (item p) is not valid. Can accept a reference to its own class item (item& p) (it is called copy constructor)
18
item t2 ( 20, 40 ) ;
item t3 ( t2 );
Dynamic constructors
Constructors can be used to allocate memory while creating objects. It is called dynamic construction of objects at run time. This is called dynamic construction of objects and is done with the help of new operator class matrix { int * p // pointer to matrix int d1, d2 public : matrix ( int n , int m ); : } matrix :: matrix (int n, int m ) { d1 = n ; d2 = m ; p = new int * [d1] ; // array pointer for ( int i= 0 ; i < d1 ; i ++) {p[i] = new int [d2] } // creates space for each row }; main ( ) { int m , n ; cin >> m >> n ; matrix A (m , n); // matrix object A is constructed with the help of constructor } Here the constructor first creates a vector pointer to an int of size d1 and then space for d2 size to each element. It is a member function whose name is the same as the class name but is preceded by tilde symbol ~ i.e., ~ item ( ) { } ; It never takes any arguments nor it returns any value It is implicitly invoked by compiler upon exiting from the program (block, function ) to clean up storage and it is good practice to declare class item { int x, y; public: item ( ) {};
Destructors
19
item ( int a, int b ) { x = a = ; y = b ; } ~ item ( ) { }; destructor } main ( ) { item t1, t2 (3, 4); : { item t3, t4, t5 (2, 3); : { } : } : } t1, t2 t3, t4, t5 are not available are not available t6 is not available item t6 (1, 4) ; :
derivedconstru (AL1, AL2, ALn , ALB): base1 (al_1), base2 (al_2), , Argument declarations for derived class constructors basen (al_n ) {Body of the derived_constru}
Actual parameters to be passed to base constructors
Declarartion
class A { : public: A (int a, int b) {};... parameterized constructor } class C { : public: C (float x) {}; ... parameterized constructor } class B : public A, public C { int t ; public: B ( int x, int y , float z , int p): A ( x, y), C ( z) { t = p; cout << "B is initialized";}; ... } B beta (2, 4. 2.5, 8)
20
<iostream.h> file
istream
<fstream.h> file
ifstream filebuf fstream ofstream
fstreambase
21
Opening and closing files : File opening can be done in two ways:
Using the constructor function of the class for opening one file using one stream. Using the member function open ( ) of the class for opening multiple files using one stream. Using constructor : file name is used to initialize the file stream object. Create a file stream object. (ifstream for input stream & ofstream for output stream) to manage the stream using the appropriate class. Initialize the file object with the desired file name. ifstream infile ( data ) ; ofstream outfile ( result ); // // input only output only
Here infile is ifstream object and attached to data file for reading and outfile is ofstream object and attached to result file for writing. We can attach the same file for writing and reading in same/ different programs. Program 1: program 2: program 3: . . . . ofstream outfile ( salary ); ifstream infile( salary ) ; ofstream outfile ( salary ); outfile . close ( ) ; ifstream infile ( salary ) ; infile . close ( )
File is closed automatically when the stream object expires (program terminates). Outfile . close ( ) disconnects the file from output stream outfile but object outfile still exists and file can be connected again. Opening files using open ( ) : Used for opening multiple files using the same stream object in sequence. ofstream outfile ; outfile . open ( data1 ) ; ; outfile . close ( ) ; outfile . open ( data2 ); ; outfile . close ( )
22
General format: file_ stream_class stream_object ; stream_object . open ( filename ); At times we may require to use two or more files simultaneously ( merging ). ifstream f1, f2 ; ofstream f3; f1 . open ( firstfile ) ; f2 . open ( secondfile ) ; f3 . open ( mergedfile ) ; Detection of End_of_file While ( f1 ) { } terminates when f1 ( object of ifstream class ) returns 0 on reaching end_of_file condition. Note that loop may terminate due to other failures as well. Another approach to detect end_of_file condition is : if ( f1 . eof ( ) ! = 0 ) { exit ( 1 ) ;} eof ( ) is a member function of ios class. It returns non zero value if the end_of_file condition is encountered and 0 otherwise. File modes general format: stream_object . open (file name , mode ); mode ios :: in ios : : out ios : : app ios : : ate ios : : nocreate ios : : noreplace meaning opens for reading only (default) opens for writing only (default) append to end_of_files. go to end_of_file on opening. open fails if file does not exist. open fails if file already exists.
Append mode allows us to add data to the end of the file only(output). ios :: ate permits us to add or modify the existing data anywhere in the file. Creating a stream using ifstream & ofstream requires no mode.The class fstream does not provide a mode by default and must be specified explicitly. Mode can combine two or more parameters using OR operator ( | ) as fout . open ( data , ios : : app / ios : : nocreate )
Sequential Input / output operations put ( ) and get ( ) functions handle single character ( write & read ) to the associated stream. fstream f 1 ; f 1. open ( Text , ios : : in | ios : : out ) ; f 1. get (ch ) ; // gets a character from file f 1. put ( ch ); // puts a character to file write ( ) and read ( ) functions handle the data in binary form ( stored in the disk file in the same format in which they are stored in internal memory ) infile . read ( ( char * ) &x , sizeof (x) ) ; outfile .write ( ( char * ) &x , sizeof (x) ) ; These functions take two arguments. o first is the address of the variable x. o second is the length of that variable in bytes. The address of the variable must be cast to type char * (pointer to character type)
23
Infile . seekg(10) moves pointer to the byte number 10 In the statement p = fileout . tellp( ), p is assigned the number of bytes in the file. seekg(offset, refposition): offset is number of bytes a file pointer has to move from the location specified by the parameter refposition which takes one of the following three constants defined in ios class. ios :: beg ios :: cur ios :: end start of the file current position of the pointer end of the file