What is C++? C++ also allows us to create hierarchy related objects. All C programs are also C++ programs with few differences.

Size: px
Start display at page:

Download "What is C++? C++ also allows us to create hierarchy related objects. All C programs are also C++ programs with few differences."

Transcription

1 What is C++? 1 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>. Cascading of I/O operators In the statement cin >> num1 >> num2, the values are assigned from left to right. In the statement cout << sum= << sum << \n, first sends the string sum= to cout and then sends the value of sum and finally it to sends the new line char. Comments In C In C ++ /* comments */ /* comments for multiple lines */ // single comment line and can t be inserted within the text of a rogram. Structure of C++ program Include files Class declaration Class functions definitions Main function program Data types of C++ User_ defined Built_in Derived type structure int array union char function class float pointer enumerated double void

2 2 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 can t 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; // address of x is assigned to i *i = 50; /* 50 value assigned to a location pointed out by i through indirection. */ Void (Available in C & C++ both) to specify the return type of a function that does not return any value to indicate empty argument list to a function to declare generic pointers in C++ void *p ; int *i ; p = i ; // assigns i pointer to void pointer p i = p ; // not allowed void pointer p can be assigned a pointer value of any basic data types. void pointer may not be dereferenced 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

3 3 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); Scope resolution operator 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 ; Memory management with pointers Along with malloc() & calloc(), C++ also defines two unary operators new and delete. These operate memory on the free store (also called free store operators). Life time of an object is directly under our control & unrelated to a block structure. Object created with new will remain until destroyed using delete. pointer_var = new data_type; (Including user defined) int *p; float *q; int *p = new int; : float *q = new float; p = new int; q = new float; 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.

4 4 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.

5 If exact match is not found then it performs internal conversions such as char int; float long ; int float; float int etc. 5 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 can t 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 Classes and Objects A class is an extension of an idea of structure used in C. A new way of creating and implementing a user defined data type. struct data type can not be treated like built-in type. If we define struct comp {float x; float y; c1, c2, c3 then, c3= c1 +c2 is not possible. Another important limitation of structures is that they do not permit data hiding. Members of a structure can be directly accessed anywhere within their scope. C++ attempts to bring user defined types as close as possible to the built in data types and also provides a facility to hide the data which is an important concept of OOP. Class It is a data type in C++ which holds data and functions. It has two parts: Class declaration (same as structure declaration) Class function definition (describes how the functions are implement) General form of class

6 6 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: { 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; Defining member functions Inside the class : { int num; float cost; public: void gdata (int a, float b) { num = a; cost = b; ; void putdata (void) { cout << num << \n ; cout << cost << \n ; When a function is defined inside a class it is treated as an inline function that means only small functions are defined insides the class. Outside the class : return_type class_name :: fun_name (arg list dec) { body Class_name tells compiler that fun-name belongs to which class { 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

7 Good practice is to define the member functions outside the class. We can also define such functions as inline by just using qualifier inline. { 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 7 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. Memory Allocation for Object When class is declared, member functions are created and placed in the memory space only once. When an object is declared as a specific class type, same member functions are used and no separate allocation is done. But space for member variables is allocated for each object. Static member variables Used to maintain values common to entire class. Each static member variable must be defined before the class definition.(as they are stored separately rather than as a part of an objects) All objects share same copy of static variable. They are associated with class rather than object, so called class variables. They are visible only within the class but its lifetime is the entire program. It is initialized to zero when the first object of its class is created. { static int count;

8 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 8 Static member functions Static function can have access to static members (functions / variables ) declared in the same class. Static member function can be called using the class name (instead of its objects). item :: static_fun is a call to static function and t1. fun_name is call to ordinary function where t1 is an object. Arrays of objects item a[10]; a[i]. getdata; a[i]. getcount; Objects as arguments in the Function There are two ways of passing object as a parameter. call by value : A copy of the entire object is passed to the function. call by reference: Only the address of the object is transferred to the function. Object can be passed to member functions of the same class / to a non member function. { int num; public : void getdata (int a ) { num = a; void add (item s1, item &s2 ) { cout << s1.num + s2.num ; 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);

9 9 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) ; Constant Member Function If member function does not alter any data in the class, we may declare it as const member function by appending a function declaration with the qualifier const. void mult (int, int) const ; error message is generated if such function tries to alter the data. 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. { int m; public : void show ( ) ; Pointer to the members of a 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 ). 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. Dereferencing * 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 Inheritance : Extending classes C++ strongly supports the concept of reusability. Its classes can be reused by creating new classes and reusing the properties of existing. New class can be derived from an old classes. This is called inheritance. Old class is referred to as the base class and the new one is called the derived class. Derived class inherits some or all properties from the base class. Single inheritance : Derived class has only one base class. Multiple inheritance : Derived class with several base classes. Hierarchical inheritance : One class is inherited by more than one classes. Multi level inheritance : Deriving a class from another derived class. Hybrid inheritance : (multilevel and multiple inheritance)

10 10 Defining derived class General format is: class d-class: visibility-mode base_class {.. Visibility modes : private or public Default visibility mode is private. Private Visibility mode class d_class : private base_class {... Here public members of base_class become private members of the derived class. The public members of base_class can only be accessed by the member functions of the derived class. Object of the derived class can not inherit private members of base class. Public members of base class even can not be accessed by objects of derived class. Public visibility mode class d_class : public base_class {... Public members of base_class become public members of d_class also and thus objects of d_class can access them by dot operator. Note that private members of the b_class are not inherited in both the cases. Derived class can have its own private and public members that extend the capabilities of the existing classes. class B { int a; public: int b; void get_ab ( ); void get_a ( ); void show_a ( ); ; // end of base class B class D : private B { int c; public: void mul ( ) ; void display ( ); ; // end of derived class D class E : public B { int d; public : void add ( ) ; void show ( ) ; ; // End of derived class E The declaration D p declares p to be an object of type class D. Here p can not access members (private or public) of base class B. The declaration E p declares p to be an object of type class E. Here p can access only public members of base class B. Making private members inheritable If private data needs to be inherited by a derived class, then one way is to make them public. But it eliminates the advantage of data hiding. C++ provides alternative visibility modifier called protected mode which serves this purpose of limited inheritance. Protected members are accessible by the member functions of its own class and any class immediately derived from it. class ABC { privates: /* optional, visible to member functions within class */ protected: /* visible to its member functions and immediate derived class */ public: /* visible to all function in the program */

11 Keywords may appear in any order and in any number of times in the class 11 Protected visibility of inherited members Protected members, when inherited in public mode, it becomes protected in the derived class too and thus ready for further inheritance. Protected members when inherited in private mode becomes private and not available for further inheritance. Declarations for various inheritance Single inheritance class A {... ; class B : public A { ; class C : private A { ; Multiple inheritance class A { ; class B { ; class C : public A, private B { ; Multilevel Inheritance class A {.. ; class B : public A { ; class C : public B { ; class D: public C {.; Hierarchical Inheritance class A {.. ; class B : public A { ; class C : private A { ; class D : public A {.; Hybrid inheritance (combination of multilevel or multiple inheritance Diagram) class A {. ; class B : public A { ; class C : private A{ ; class D : public B, private C { ; Here D (child) inherits from its base (parent) classes which has a common base class A called grand parent. In such situations child inherits from grand parent via two separate paths. Grand parent is sometimes referred to as indirect base class. Such inheritance might pose some problems as all public & protected members of grand parent are inherited into child twice first via parent_1 and again via parent_2. This creates ambiguity and should be avoided. Virtual Base classes Declare ancestor class as a virtual base class (Only one copy of A will be inherited by D) class A { ; class B : virtual public A { ; class C : public virtual A { ; // Order is immaterial class D : public A, public B {...; 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 :: Characteristics of friend function It is not in the scope of the class to which it has been declared as friend. So it can not be called using the object of that class. It can be invoked like a normal function without the help of any object. It can not access the members directly and has to use an object_name and dot membership operator with each member name. It can be declared either in public or private part of a class without affecting its meaning. 12

13 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 ; Rules for Overloading Operators Only existing operators can be overloaded. Overloaded operator must have at least one operand that is user-defined type. Some operators can not be overloaded. (e.g.,..* ::? sizeof ) We cannot change the basic meaning of an operator. ( e.g., + can t be used for subtraction) Binary arithmetic operators must explicitly return a value. Binary operators when overloaded through a member functions then left hand operand be an object of the relevant class.

14 It is possible to have more than one definition for any operator. String operator+ ( string ) ; Vector operator+ ( vector ) ; Matrix operator + ( matrix ) ; Polymorphism 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 14 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? Pointers to objects o Pointer can point to an object created by a class and are useful in creating objects at run time such as item *ptr ; o Here item is a class with two public functions, say, void get_data ( int a, float b) and void show ( void ). o Object pointer can access the public members ( data / function ) of an object. Assume the following declarations: item x ; item *ptr = &x; o 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 15 o Objects using pointers are created using new operator as item *ptr = new item; o 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. 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 Rules for virtual functions The virtual functions must be members of some class. They can not be static members. They are accessed by using object pointers. A virtual function can be a friend of another class. We cannot have virtual constructors but can have virtual destructors. When a base pointer points to derived class, incrementing or decrementing pointer (i.e., pointing to next or previous object) will not be allowed. 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 Constructors and Destructors Member function for initializing private variables of a class can be included in public part of the class. { int x; int y; public : void getdata (int a, int b) { x = a; y = b Objects of are created by declaration item p, q; Explicit call is made to member function getdata for each object to initialize the private variables of p and q. 16

17 17 These functions can t 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. C++ provides this facility. Constructor Enables an object to initialize itself when it is created (automatic). Destructor Destroys the object when they are no longer required. Constructor: has the same name as of class { int x; int y; public: item (void) constructor { x = 0; y = 0; Elements of item type are declared as: item p, q, r. Here p, q and r are initialized to 0. Constructor that accepts no parameters is called default constructor Special characteristics of constructor functions: Should be declared in public part. Are invoked automatically when objects are created. Do not have return type, not even void. Can not be inherited though derived class can call the base constructor. Like other C++ functions, they can have default arguments. Can not be referenced through their address. These function use implicit call to operators new and delete when memory allocation is required. Parameterized constructors Now declaration item p will not work { int x; int y; public : item(int a, int b ) parameterized constructor { x = a; y = b 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 (item& p) (it is called copy constructor) Multiple constructors in a class { int x, y; public:

18 Overloading of item ( ) {x = 0; y = 0 ; Constructors item ( int a, int b) { x = a; y = b ; item (item & p) { x = p. x ; y = p. y ; Possible declarations item t1; item t2 ( 20, 40 ) ; item t3 ( t2 ); 18 Implicit constructor (provided by compiler C++) Creates objects even though constructor is not defined in the class. In case if we define a constructor, we must also define do-nothing constructor such as item ( ) { ; Constructors with default Argument values Constructor definition item ( int a, int b = 2) { x = a; y = b; Object declaration item t (3) ; Here t. x = 3; t. y = 2; default value item t1 (4,3); then t1. x = 4; t1. y = 3; The missing arguments must be the trailing ones 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. Destructors 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 { int x, y; public: item ( ) {;

19 19 item ( int a, int b ) { x = a = ; y = b ; ~ item ( ) { ; destructor main ( ) { item t1, t2 (3, 4); : { item t3, t4, t5 (2, 3); : { item t6 (1, 4) ; : : t6 is not available : t3, t4, t5 are not available t1, t2 are not available Constructors in derived classes If base class has constructor without arguments then derived class need not have a constructor function. If any base class contains constructor with one or more arguments, then it is mandatory for the derived class to have a constructor and pass the arguments to the base class constructors. The general format Argument declarations of base constructors ` derived constru (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 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";;... Declarartion B beta (2, , 8)

20 Unformated I/O Operations 20 ios : istream, ostream, iostream (ios is a general purpose I/O stream). istream is an input stream that declares input functions such as get ( ), getline ( ) and read( ). Overloaded extraction operator is >>. ostream is an output stream that declares output functions such as put ( ) and write ( ). Overloaded insertion operator is <<. iostream is an input/output stream. cin and cout are objects defined in <iostream.h> file for input / output of data of various types. cin >> v1 >> v2 >> >> vn ; and cout << v1 << v2 <<. << vm ; put ( ) and get ( ) functions of cout and cin objects respectively, handle single character input / output operations get ( ) char c ; c = cin. get ( ) cin. get ( c ) cin >> c (will not work properly) put ( ) cout. put (c) // displays the value of c cout. put ( 68 ) // displays character D whose ASCII value of 68 get line ( ) reads line ( terminated by new line character \n ) cin. getline ( line, size) line is a variable which stores characters of line. Termination takes place when size 1 or "\n" which ever occurs first. We can read string ( without blanks in it ) by cin >> name ; write ( ) displays an entire line by writing cout. write ( line, size ); Concatenation of two strings can be displayed as follows: cout. write ( string1, m ). write ( string2, n ); OR cout. write ( string1, m ); cout. write ( string2, n ) ; Working with files A program involves two types of data communication: Data transfer between console unit and the program. Data transfer between the program and a disk file. I/O system of C++ handles file operations similar to console input & output operations. C ++ contains a set of classes that define the file handling methods. ifstream ofstream fstream These classes are derived from fstreambase class and from the corresponding classes in <iostream.h> file. These classes (designed to manage the files) are declared in <fstream.h> <iostream.h> file ios istream streambuf ostream iostream <fstream.h> file ifstream filebuf fstream ofstream fstreambase

21 Details of the <file stream> classes 21 class contents filebuf - sets the file buffers to read and write. fstreambase - provides operations common to the file streams. It is a base for fstream, fstream & ofstream classes. It contains open ( ) & close ( ) funcs. ifstream - provides input operations. Inherits various functions from istream ( get ( ), get line ( ), read ( ), seek ( ).. ), It contains open( ) with default input mode. ofstream - provides output operations. Inherits various functions from ostream ( put, seekp, tellp, write etc.). It contains open ( ) with default output mode. fstream - supports for simultaneous input/output operations. Inherits all functions from istream, ostream classes through iostream. It contains open ( ) with default input mode. 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 ) ; // input only ofstream outfile ( result ); // 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: ofstream outfile ( salary ); program 2: ifstream infile( salary ) ; program 3:. 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 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 Reading and writing a class object 23 write ( ) copies a class object from memory, byte by byte with no conversion. Only data members are written to the file and not the member functions. read ( ) reads a class object from file to the memory. in_ ; fstream f ; f.open ( stock.dat, ios :: in / ios :: out) ;. f.write (( char *)) &item, sizeof (item) ) ; f. seekg (0) ; // reset to the start f. read ( ( char * ) &item, sizeof ( item) );.. f. close ( ); Functions for manipulating seekg ( ) moves input pointer to a specified location. seekp ( ) moves output pointer to a specified location tellg ( ) gives the current position of input pointer. tellp ( ) gives the current position of output pointer. 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 Random Access ( Updation ) If file contains a collection of items/objects of equal length, then to move to a particular (mth ) object, following is done. int ob_length = sizeof ( object ) ; int loc = m * ob_length ; seekg ( loc ); or seekp ( loc ) ; o loc is the start address of mth object. o Total number of objects in a file can be found using ob_length as follows : int n = file_size / ob_length ; o file_size can be obtained using tellg ( ) / tellp ( ) when the file pointer is located at the end of the file.

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement?

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement? 1. Distinguish & and && operators. PART-A Questions 2. How does an enumerated statement differ from a typedef statement? 3. What are the various members of a class? 4. Who can access the protected members

More information

Multichoice Quetions 1. Atributes a. are listed in the second part of the class box b. its time is preceded by a colon. c. its default value is

Multichoice Quetions 1. Atributes a. are listed in the second part of the class box b. its time is preceded by a colon. c. its default value is Multichoice Quetions 1. Atributes a. are listed in the second part of the class box b. its time is preceded by a colon. c. its default value is preceded by an equal sign d. its name has undereline 2. Associations

More information

C++ INTERVIEW QUESTIONS

C++ INTERVIEW QUESTIONS C++ INTERVIEW QUESTIONS http://www.tutorialspoint.com/cplusplus/cpp_interview_questions.htm Copyright tutorialspoint.com Dear readers, these C++ Interview Questions have been designed specially to get

More information

13 Classes & Objects with Constructors/Destructors

13 Classes & Objects with Constructors/Destructors 13 Classes & Objects with Constructors/Destructors 13.1 Introduction In object oriented programming, the emphasis is on data rather than function. Class is a way that binds the data & function together.

More information

KITES TECHNOLOGY COURSE MODULE (C, C++, DS)

KITES TECHNOLOGY COURSE MODULE (C, C++, DS) KITES TECHNOLOGY 360 Degree Solution www.kitestechnology.com/academy.php info@kitestechnology.com technologykites@gmail.com Contact: - 8961334776 9433759247 9830639522.NET JAVA WEB DESIGN PHP SQL, PL/SQL

More information

The C Programming Language course syllabus associate level

The C Programming Language course syllabus associate level TECHNOLOGIES The C Programming Language course syllabus associate level Course description The course fully covers the basics of programming in the C programming language and demonstrates fundamental programming

More information

Basics of I/O Streams and File I/O

Basics of I/O Streams and File I/O Basics of This is like a cheat sheet for file I/O in C++. It summarizes the steps you must take to do basic I/O to and from files, with only a tiny bit of explanation. It is not a replacement for reading

More information

Object Oriented Programming With C++(10CS36) Question Bank. UNIT 1: Introduction to C++

Object Oriented Programming With C++(10CS36) Question Bank. UNIT 1: Introduction to C++ Question Bank UNIT 1: Introduction to C++ 1. What is Procedure-oriented Programming System? Dec 2005 2. What is Object-oriented Programming System? June 2006 3. Explain the console I/O functions supported

More information

Subject Name: Object Oriented Programming in C++ Subject Code: 2140705

Subject Name: Object Oriented Programming in C++ Subject Code: 2140705 Faculties: L.J. Institute of Engineering & Technology Semester: IV (2016) Subject Name: Object Oriented Programming in C++ Subject Code: 21405 Sr No UNIT - 1 : CONCEPTS OF OOCP Topics -Introduction OOCP,

More information

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program. Name: Class: Date: Exam #1 - Prep True/False Indicate whether the statement is true or false. 1. Programming is the process of writing a computer program in a language that the computer can respond to

More information

www.sahajsolns.com Chapter 4 OOPS WITH C++ Sahaj Computer Solutions

www.sahajsolns.com Chapter 4 OOPS WITH C++ Sahaj Computer Solutions Chapter 4 OOPS WITH C++ Sahaj Computer Solutions 1 Session Objectives Classes and Objects Class Declaration Class Members Data Constructors Destructors Member Functions Class Member Visibility Private,

More information

El Dorado Union High School District Educational Services

El Dorado Union High School District Educational Services El Dorado Union High School District Course of Study Information Page Course Title: ACE Computer Programming II (#495) Rationale: A continuum of courses, including advanced classes in technology is needed.

More information

C++ Programming Language

C++ Programming Language C++ Programming Language Lecturer: Yuri Nefedov 7th and 8th semesters Lectures: 34 hours (7th semester); 32 hours (8th semester). Seminars: 34 hours (7th semester); 32 hours (8th semester). Course abstract

More information

Glossary of Object Oriented Terms

Glossary of Object Oriented Terms Appendix E Glossary of Object Oriented Terms abstract class: A class primarily intended to define an instance, but can not be instantiated without additional methods. abstract data type: An abstraction

More information

Storage Classes CS 110B - Rule Storage Classes Page 18-1 \handouts\storclas

Storage Classes CS 110B - Rule Storage Classes Page 18-1 \handouts\storclas CS 110B - Rule Storage Classes Page 18-1 Attributes are distinctive features of a variable. Data type, int or double for example, is an attribute. Storage class is another attribute. There are four storage

More information

C++ Programming: From Problem Analysis to Program Design, Fifth Edition. Chapter 3: Input/Output

C++ Programming: From Problem Analysis to Program Design, Fifth Edition. Chapter 3: Input/Output C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 3: Input/Output Objectives In this chapter, you will: Learn what a stream is and examine input and output streams Explore

More information

Java Interview Questions and Answers

Java Interview Questions and Answers 1. What is the most important feature of Java? Java is a platform independent language. 2. What do you mean by platform independence? Platform independence means that we can write and compile the java

More information

Simple C++ Programs. Engineering Problem Solving with C++, Etter/Ingber. Dev-C++ Dev-C++ Windows Friendly Exit. The C++ Programming Language

Simple C++ Programs. Engineering Problem Solving with C++, Etter/Ingber. Dev-C++ Dev-C++ Windows Friendly Exit. The C++ Programming Language Simple C++ Programs Engineering Problem Solving with C++, Etter/Ingber Chapter 2 Simple C++ Programs Program Structure Constants and Variables C++ Operators Standard Input and Output Basic Functions from

More information

C++ Input/Output: Streams

C++ Input/Output: Streams C++ Input/Output: Streams 1 The basic data type for I/O in C++ is the stream. C++ incorporates a complex hierarchy of stream types. The most basic stream types are the standard input/output streams: istream

More information

Object Oriented Software Design II

Object Oriented Software Design II Object Oriented Software Design II Introduction to C++ Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa February 20, 2012 G. Lipari (Scuola Superiore Sant Anna) C++ Intro February

More information

PROBLEM SOLVING SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON

PROBLEM SOLVING SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON PROBLEM SOLVING WITH SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON Addison Wesley Boston San Francisco New York London

More information

ALLIED PAPER : DISCRETE MATHEMATICS (for B.Sc. Computer Technology & B.Sc. Multimedia and Web Technology)

ALLIED PAPER : DISCRETE MATHEMATICS (for B.Sc. Computer Technology & B.Sc. Multimedia and Web Technology) ALLIED PAPER : DISCRETE MATHEMATICS (for B.Sc. Computer Technology & B.Sc. Multimedia and Web Technology) Subject Description: This subject deals with discrete structures like set theory, mathematical

More information

Member Functions of the istream Class

Member Functions of the istream Class Member Functions of the istream Class The extraction operator is of limited use because it always uses whitespace to delimit its reads of the input stream. It cannot be used to read those whitespace characters,

More information

Course Name: ADVANCE COURSE IN SOFTWARE DEVELOPMENT (Specialization:.Net Technologies)

Course Name: ADVANCE COURSE IN SOFTWARE DEVELOPMENT (Specialization:.Net Technologies) Course Name: ADVANCE COURSE IN SOFTWARE DEVELOPMENT (Specialization:.Net Technologies) Duration of Course: 6 Months Fees: Rs. 25,000/- (including Service Tax) Eligibility: B.E./B.Tech., M.Sc.(IT/ computer

More information

Java (12 Weeks) Introduction to Java Programming Language

Java (12 Weeks) Introduction to Java Programming Language Java (12 Weeks) Topic Lecture No. Introduction to Java Programming Language 1 An Introduction to Java o Java as a Programming Platform, The Java "White Paper" Buzzwords, Java and the Internet, A Short

More information

Chapter 2: Elements of Java

Chapter 2: Elements of Java Chapter 2: Elements of Java Basic components of a Java program Primitive data types Arithmetic expressions Type casting. The String type (introduction) Basic I/O statements Importing packages. 1 Introduction

More information

IS0020 Program Design and Software Tools Midterm, Feb 24, 2004. Instruction

IS0020 Program Design and Software Tools Midterm, Feb 24, 2004. Instruction IS0020 Program Design and Software Tools Midterm, Feb 24, 2004 Name: Instruction There are two parts in this test. The first part contains 50 questions worth 80 points. The second part constitutes 20 points

More information

Chapter 5 Names, Bindings, Type Checking, and Scopes

Chapter 5 Names, Bindings, Type Checking, and Scopes Chapter 5 Names, Bindings, Type Checking, and Scopes Chapter 5 Topics Introduction Names Variables The Concept of Binding Type Checking Strong Typing Scope Scope and Lifetime Referencing Environments Named

More information

Illustration 1: Diagram of program function and data flow

Illustration 1: Diagram of program function and data flow The contract called for creation of a random access database of plumbing shops within the near perimeter of FIU Engineering school. The database features a rating number from 1-10 to offer a guideline

More information

Sources: On the Web: Slides will be available on:

Sources: On the Web: Slides will be available on: C programming Introduction The basics of algorithms Structure of a C code, compilation step Constant, variable type, variable scope Expression and operators: assignment, arithmetic operators, comparison,

More information

BCS2B02: OOP Concepts and Data Structures Using C++

BCS2B02: OOP Concepts and Data Structures Using C++ SECOND SEMESTER BCS2B02: OOP Concepts and Data Structures Using C++ Course Number: 10 Contact Hours per Week: 4 (2T + 2P) Number of Credits: 2 Number of Contact Hours: 30 Hrs. Course Evaluation: Internal

More information

Syllabus OBJECT ORIENTED PROGRAMMING C++

Syllabus OBJECT ORIENTED PROGRAMMING C++ 1 Syllabus OBJECT ORIENTED PROGRAMMING C++ 1. Introduction : What is object oriented programming? Why do we need objectoriented. Programming characteristics of object-oriented languages. C and C++. 2.

More information

Course notes Standard C++ programming

Course notes Standard C++ programming Department of Cybernetics The University of Reading SE2B2 Further Computer Systems Course notes Standard C++ programming by Dr Virginie F. Ruiz November, 03 CREATING AND USING A COPY CONSTRUCTOR... 27

More information

C++ Language Tutorial

C++ Language Tutorial cplusplus.com C++ Language Tutorial Written by: Juan Soulié Last revision: June, 2007 Available online at: http://www.cplusplus.com/doc/tutorial/ The online version is constantly revised and may contain

More information

5 Arrays and Pointers

5 Arrays and Pointers 5 Arrays and Pointers 5.1 One-dimensional arrays Arrays offer a convenient way to store and access blocks of data. Think of arrays as a sequential list that offers indexed access. For example, a list of

More information

Keywords are identifiers having predefined meanings in C programming language. The list of keywords used in standard C are : unsigned void

Keywords are identifiers having predefined meanings in C programming language. The list of keywords used in standard C are : unsigned void 1. Explain C tokens Tokens are basic building blocks of a C program. A token is the smallest element of a C program that is meaningful to the compiler. The C compiler recognizes the following kinds of

More information

Module 816. File Management in C. M. Campbell 1993 Deakin University

Module 816. File Management in C. M. Campbell 1993 Deakin University M. Campbell 1993 Deakin University Aim Learning objectives Content After working through this module you should be able to create C programs that create an use both text and binary files. After working

More information

Course Title: Software Development

Course Title: Software Development Course Title: Software Development Unit: Customer Service Content Standard(s) and Depth of 1. Analyze customer software needs and system requirements to design an information technology-based project plan.

More information

Lecture 11 Doubly Linked Lists & Array of Linked Lists. Doubly Linked Lists

Lecture 11 Doubly Linked Lists & Array of Linked Lists. Doubly Linked Lists Lecture 11 Doubly Linked Lists & Array of Linked Lists In this lecture Doubly linked lists Array of Linked Lists Creating an Array of Linked Lists Representing a Sparse Matrix Defining a Node for a Sparse

More information

Database Programming with PL/SQL: Learning Objectives

Database Programming with PL/SQL: Learning Objectives Database Programming with PL/SQL: Learning Objectives This course covers PL/SQL, a procedural language extension to SQL. Through an innovative project-based approach, students learn procedural logic constructs

More information

Chapter 13 Storage classes

Chapter 13 Storage classes Chapter 13 Storage classes 1. Storage classes 2. Storage Class auto 3. Storage Class extern 4. Storage Class static 5. Storage Class register 6. Global and Local Variables 7. Nested Blocks with the Same

More information

C Interview Questions

C Interview Questions http://techpreparation.com C Interview Questions And Answers 2008 V i s i t T e c h P r e p a r a t i o n. c o m f o r m o r e i n t e r v i e w q u e s t i o n s a n d a n s w e r s C Interview Questions

More information

Informatica e Sistemi in Tempo Reale

Informatica e Sistemi in Tempo Reale Informatica e Sistemi in Tempo Reale Introduction to C programming Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa October 25, 2010 G. Lipari (Scuola Superiore Sant Anna)

More information

C++FA 5.1 PRACTICE MID-TERM EXAM

C++FA 5.1 PRACTICE MID-TERM EXAM C++FA 5.1 PRACTICE MID-TERM EXAM This practicemid-term exam covers sections C++FA 1.1 through C++FA 1.4 of C++ with Financial Applications by Ben Van Vliet, available at www.benvanvliet.net. 1.) A pointer

More information

I PUC - Computer Science. Practical s Syllabus. Contents

I PUC - Computer Science. Practical s Syllabus. Contents I PUC - Computer Science Practical s Syllabus Contents Topics 1 Overview Of a Computer 1.1 Introduction 1.2 Functional Components of a computer (Working of each unit) 1.3 Evolution Of Computers 1.4 Generations

More information

10CS35: Data Structures Using C

10CS35: Data Structures Using C CS35: Data Structures Using C QUESTION BANK REVIEW OF STRUCTURES AND POINTERS, INTRODUCTION TO SPECIAL FEATURES OF C OBJECTIVE: Learn : Usage of structures, unions - a conventional tool for handling a

More information

Chapter One Introduction to Programming

Chapter One Introduction to Programming Chapter One Introduction to Programming 1-1 Algorithm and Flowchart Algorithm is a step-by-step procedure for calculation. More precisely, algorithm is an effective method expressed as a finite list of

More information

1) The postfix expression for the infix expression A+B*(C+D)/F+D*E is ABCD+*F/DE*++

1) The postfix expression for the infix expression A+B*(C+D)/F+D*E is ABCD+*F/DE*++ Answer the following 1) The postfix expression for the infix expression A+B*(C+D)/F+D*E is ABCD+*F/DE*++ 2) Which data structure is needed to convert infix notations to postfix notations? Stack 3) The

More information

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner. Handout 1 CS603 Object-Oriented Programming Fall 15 Page 1 of 11 Handout 1 Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner. Java

More information

Chapter 5 Functions. Introducing Functions

Chapter 5 Functions. Introducing Functions Chapter 5 Functions 1 Introducing Functions A function is a collection of statements that are grouped together to perform an operation Define a function Invoke a funciton return value type method name

More information

PL/SQL Overview. Basic Structure and Syntax of PL/SQL

PL/SQL Overview. Basic Structure and Syntax of PL/SQL PL/SQL Overview PL/SQL is Procedural Language extension to SQL. It is loosely based on Ada (a variant of Pascal developed for the US Dept of Defense). PL/SQL was first released in ١٩٩٢ as an optional extension

More information

Binary storage of graphs and related data

Binary storage of graphs and related data EÖTVÖS LORÁND UNIVERSITY Faculty of Informatics Department of Algorithms and their Applications Binary storage of graphs and related data BSc thesis Author: Frantisek Csajka full-time student Informatics

More information

Object Oriented Software Design

Object Oriented Software Design Object Oriented Software Design Introduction to Java - II Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa October 28, 2010 G. Lipari (Scuola Superiore Sant Anna) Introduction

More information

C++ Outline. cout << "Enter two integers: "; int x, y; cin >> x >> y; cout << "The sum is: " << x + y << \n ;

C++ Outline. cout << Enter two integers: ; int x, y; cin >> x >> y; cout << The sum is:  << x + y << \n ; C++ Outline Notes taken from: - Drake, Caleb. EECS 370 Course Notes, University of Illinois Chicago, Spring 97. Chapters 9, 10, 11, 13.1 & 13.2 - Horstman, Cay S. Mastering Object-Oriented Design in C++.

More information

WORKSPACE WEB DEVELOPMENT & OUTSOURCING TRAINING CENTER

WORKSPACE WEB DEVELOPMENT & OUTSOURCING TRAINING CENTER WORKSPACE WEB DEVELOPMENT & OUTSOURCING TRAINING CENTER Course Outline (2015) Basic Programming With Procedural & Object Oriented Concepts (C, C++) Training Office# Road: 11, House: 1 A, Nikunja 2, Khilkhet,

More information

Lecture 3. Arrays. Name of array. c[0] c[1] c[2] c[3] c[4] c[5] c[6] c[7] c[8] c[9] c[10] c[11] Position number of the element within array c

Lecture 3. Arrays. Name of array. c[0] c[1] c[2] c[3] c[4] c[5] c[6] c[7] c[8] c[9] c[10] c[11] Position number of the element within array c Lecture 3 Data structures arrays structs C strings: array of chars Arrays as parameters to functions Multiple subscripted arrays Structs as parameters to functions Default arguments Inline functions Redirection

More information

/* File: blkcopy.c. size_t n

/* File: blkcopy.c. size_t n 13.1. BLOCK INPUT/OUTPUT 505 /* File: blkcopy.c The program uses block I/O to copy a file. */ #include main() { signed char buf[100] const void *ptr = (void *) buf FILE *input, *output size_t

More information

Operator Overloading. Lecture 8. Operator Overloading. Running Example: Complex Numbers. Syntax. What can be overloaded. Syntax -- First Example

Operator Overloading. Lecture 8. Operator Overloading. Running Example: Complex Numbers. Syntax. What can be overloaded. Syntax -- First Example Operator Overloading Lecture 8 Operator Overloading C++ feature that allows implementer-defined classes to specify class-specific function for operators Benefits allows classes to provide natural semantics

More information

Curriculum Map. Discipline: Computer Science Course: C++

Curriculum Map. Discipline: Computer Science Course: C++ Curriculum Map Discipline: Computer Science Course: C++ August/September: How can computer programs make problem solving easier and more efficient? In what order does a computer execute the lines of code

More information

Object Oriented Software Design

Object Oriented Software Design Object Oriented Software Design Introduction to Java - II Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa September 14, 2011 G. Lipari (Scuola Superiore Sant Anna) Introduction

More information

JAVA - QUICK GUIDE. Java SE is freely available from the link Download Java. So you download a version based on your operating system.

JAVA - QUICK GUIDE. Java SE is freely available from the link Download Java. So you download a version based on your operating system. http://www.tutorialspoint.com/java/java_quick_guide.htm JAVA - QUICK GUIDE Copyright tutorialspoint.com What is Java? Java is: Object Oriented Platform independent: Simple Secure Architectural- neutral

More information

Lab 2 - CMPS 1043, Computer Science I Introduction to File Input/Output (I/O) Projects and Solutions (C++)

Lab 2 - CMPS 1043, Computer Science I Introduction to File Input/Output (I/O) Projects and Solutions (C++) Lab 2 - CMPS 1043, Computer Science I Introduction to File Input/Output (I/O) Projects and Solutions (C++) (Revised from http://msdn.microsoft.com/en-us/library/bb384842.aspx) * Keep this information to

More information

Basic Object-Oriented Programming in Java

Basic Object-Oriented Programming in Java core programming Basic Object-Oriented Programming in Java 1 2001-2003 Marty Hall, Larry Brown http:// Agenda Similarities and differences between Java and C++ Object-oriented nomenclature and conventions

More information

Moving from CS 61A Scheme to CS 61B Java

Moving from CS 61A Scheme to CS 61B Java Moving from CS 61A Scheme to CS 61B Java Introduction Java is an object-oriented language. This document describes some of the differences between object-oriented programming in Scheme (which we hope you

More information

arrays C Programming Language - Arrays

arrays C Programming Language - Arrays arrays So far, we have been using only scalar variables scalar meaning a variable with a single value But many things require a set of related values coordinates or vectors require 3 (or 2, or 4, or more)

More information

Computer Programming I

Computer Programming I Computer Programming I COP 2210 Syllabus Spring Semester 2012 Instructor: Greg Shaw Office: ECS 313 (Engineering and Computer Science Bldg) Office Hours: Tuesday: 2:50 4:50, 7:45 8:30 Thursday: 2:50 4:50,

More information

Compiler Construction

Compiler Construction Compiler Construction Lecture 1 - An Overview 2003 Robert M. Siegfried All rights reserved A few basic definitions Translate - v, a.to turn into one s own language or another. b. to transform or turn from

More information

System Calls and Standard I/O

System Calls and Standard I/O System Calls and Standard I/O Professor Jennifer Rexford http://www.cs.princeton.edu/~jrex 1 Goals of Today s Class System calls o How a user process contacts the Operating System o For advanced services

More information

How To Port A Program To Dynamic C (C) (C-Based) (Program) (For A Non Portable Program) (Un Portable) (Permanent) (Non Portable) C-Based (Programs) (Powerpoint)

How To Port A Program To Dynamic C (C) (C-Based) (Program) (For A Non Portable Program) (Un Portable) (Permanent) (Non Portable) C-Based (Programs) (Powerpoint) TN203 Porting a Program to Dynamic C Introduction Dynamic C has a number of improvements and differences compared to many other C compiler systems. This application note gives instructions and suggestions

More information

AP Computer Science Java Subset

AP Computer Science Java Subset APPENDIX A AP Computer Science Java Subset The AP Java subset is intended to outline the features of Java that may appear on the AP Computer Science A Exam. The AP Java subset is NOT intended as an overall

More information

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007 Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007 The Java Type System By now, you have seen a fair amount of Java. Time to study in more depth the foundations of the language,

More information

MISRA-C:2012 Standards Model Summary for C / C++

MISRA-C:2012 Standards Model Summary for C / C++ MISRA-C:2012 Standards Model Summary for C / C++ The LDRA tool suite is developed and certified to BS EN ISO 9001:2000. This information is applicable to version 9.4.2 of the LDRA tool suite. It is correct

More information

Embedded Systems. Review of ANSI C Topics. A Review of ANSI C and Considerations for Embedded C Programming. Basic features of C

Embedded Systems. Review of ANSI C Topics. A Review of ANSI C and Considerations for Embedded C Programming. Basic features of C Embedded Systems A Review of ANSI C and Considerations for Embedded C Programming Dr. Jeff Jackson Lecture 2-1 Review of ANSI C Topics Basic features of C C fundamentals Basic data types Expressions Selection

More information

System Calls Related to File Manipulation

System Calls Related to File Manipulation KING FAHD UNIVERSITY OF PETROLEUM AND MINERALS Information and Computer Science Department ICS 431 Operating Systems Lab # 12 System Calls Related to File Manipulation Objective: In this lab we will be

More information

Java CPD (I) Frans Coenen Department of Computer Science

Java CPD (I) Frans Coenen Department of Computer Science Java CPD (I) Frans Coenen Department of Computer Science Content Session 1, 12:45-14:30 (First Java Programme, Inheritance, Arithmetic) Session 2, 14:45-16:45 (Input and Programme Constructs) Materials

More information

1 Abstract Data Types Information Hiding

1 Abstract Data Types Information Hiding 1 1 Abstract Data Types Information Hiding 1.1 Data Types Data types are an integral part of every programming language. ANSI-C has int, double and char to name just a few. Programmers are rarely content

More information

Fundamentals of Java Programming

Fundamentals of Java Programming Fundamentals of Java Programming This document is exclusive property of Cisco Systems, Inc. Permission is granted to print and copy this document for non-commercial distribution and exclusive use by instructors

More information

CS193D Handout 06 Winter 2004 January 26, 2004 Copy Constructor and operator=

CS193D Handout 06 Winter 2004 January 26, 2004 Copy Constructor and operator= CS193D Handout 06 Winter 2004 January 26, 2004 Copy Constructor and operator= We already know that the compiler will supply a default (zero-argument) constructor if the programmer does not specify one.

More information

Class XII (Theory) C++

Class XII (Theory) C++ Class XII (Theory) C++ Duration: 3 hours Total Marks: 70 Unit No. Unit Name Marks 1. OBJECT ORIENTED PROGRAMMING IN C++ 30 2. DATA STRUCTURE 14 3. DATABASE MANAGEMENT SYSTEM AND SQL 8 4. BOOLEAN ALGEBRA

More information

SUBJECT :- COMPUTER SCIENCE (083) CLASS XII. Unit-Wise Marks and Period Distribution

SUBJECT :- COMPUTER SCIENCE (083) CLASS XII. Unit-Wise Marks and Period Distribution SUBJECT :- COMPUTER SCIENCE (83) CLASS XII Unit-Wise Marks and Period Distribution Unit No. Unit Name Marks. 2. 3. 4. 5. PROGRAMMING IN C++ DATA STRUCTURE DATABASE AND SQL BOOLEAN ALGEBRA COMMUNICATION

More information

ASCII Encoding. The char Type. Manipulating Characters. Manipulating Characters

ASCII Encoding. The char Type. Manipulating Characters. Manipulating Characters The char Type ASCII Encoding The C char type stores small integers. It is usually 8 bits. char variables guaranteed to be able to hold integers 0.. +127. char variables mostly used to store characters

More information

The University of Alabama in Huntsville Electrical and Computer Engineering CPE 112 01 Test #4 November 20, 2002. True or False (2 points each)

The University of Alabama in Huntsville Electrical and Computer Engineering CPE 112 01 Test #4 November 20, 2002. True or False (2 points each) True or False (2 points each) The University of Alabama in Huntsville Electrical and Computer Engineering CPE 112 01 Test #4 November 20, 2002 1. Using global variables is better style than using local

More information

Introduction to Java

Introduction to Java Introduction to Java The HelloWorld program Primitive data types Assignment and arithmetic operations User input Conditional statements Looping Arrays CSA0011 Matthew Xuereb 2008 1 Java Overview A high

More information

UML for C# Modeling Basics

UML for C# Modeling Basics UML for C# C# is a modern object-oriented language for application development. In addition to object-oriented constructs, C# supports component-oriented programming with properties, methods and events.

More information

C Compiler Targeting the Java Virtual Machine

C Compiler Targeting the Java Virtual Machine C Compiler Targeting the Java Virtual Machine Jack Pien Senior Honors Thesis (Advisor: Javed A. Aslam) Dartmouth College Computer Science Technical Report PCS-TR98-334 May 30, 1998 Abstract One of the

More information

Polymorphism. Problems with switch statement. Solution - use virtual functions (polymorphism) Polymorphism

Polymorphism. Problems with switch statement. Solution - use virtual functions (polymorphism) Polymorphism Polymorphism Problems with switch statement Programmer may forget to test all possible cases in a switch. Tracking this down can be time consuming and error prone Solution - use virtual functions (polymorphism)

More information

CSCI 253. Object Oriented Programming (OOP) Overview. George Blankenship 1. Object Oriented Design: Java Review OOP George Blankenship.

CSCI 253. Object Oriented Programming (OOP) Overview. George Blankenship 1. Object Oriented Design: Java Review OOP George Blankenship. CSCI 253 Object Oriented Design: Java Review OOP George Blankenship George Blankenship 1 Object Oriented Programming (OOP) OO Principles Abstraction Encapsulation Abstract Data Type (ADT) Implementation

More information

PL / SQL Basics. Chapter 3

PL / SQL Basics. Chapter 3 PL / SQL Basics Chapter 3 PL / SQL Basics PL / SQL block Lexical units Variable declarations PL / SQL types Expressions and operators PL / SQL control structures PL / SQL style guide 2 PL / SQL Block Basic

More information

Boolean Expressions, Conditions, Loops, and Enumerations. Precedence Rules (from highest to lowest priority)

Boolean Expressions, Conditions, Loops, and Enumerations. Precedence Rules (from highest to lowest priority) Boolean Expressions, Conditions, Loops, and Enumerations Relational Operators == // true if two values are equivalent!= // true if two values are not equivalent < // true if left value is less than the

More information

Computer Programming C++ Classes and Objects 15 th Lecture

Computer Programming C++ Classes and Objects 15 th Lecture Computer Programming C++ Classes and Objects 15 th Lecture 엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University Copyrights 2013 Eom, Hyeonsang All Rights Reserved Outline

More information

Semantic Analysis: Types and Type Checking

Semantic Analysis: Types and Type Checking Semantic Analysis Semantic Analysis: Types and Type Checking CS 471 October 10, 2007 Source code Lexical Analysis tokens Syntactic Analysis AST Semantic Analysis AST Intermediate Code Gen lexical errors

More information

Topics. Introduction. Java History CS 146. Introduction to Programming and Algorithms Module 1. Module Objectives

Topics. Introduction. Java History CS 146. Introduction to Programming and Algorithms Module 1. Module Objectives Introduction to Programming and Algorithms Module 1 CS 146 Sam Houston State University Dr. Tim McGuire Module Objectives To understand: the necessity of programming, differences between hardware and software,

More information

PROGRAMMING IN C PROGRAMMING IN C CONTENT AT A GLANCE

PROGRAMMING IN C PROGRAMMING IN C CONTENT AT A GLANCE PROGRAMMING IN C CONTENT AT A GLANCE 1 MODULE 1 Unit 1 : Basics of Programming Unit 2 : Fundamentals Unit 3 : C Operators MODULE 2 unit 1 : Input Output Statements unit 2 : Control Structures unit 3 :

More information

COMPUTER SCIENCE 1999 (Delhi Board)

COMPUTER SCIENCE 1999 (Delhi Board) COMPUTER SCIENCE 1999 (Delhi Board) Time allowed: 3 hours Max. Marks: 70 Instructions: (i) All the questions are compulsory. (ii) Programming Language: C++ QUESTION l. (a) Why main function is special?

More information

Introduction to C++ Introduction to C++ Week 7 Dr Alex Martin 2013 Slide 1

Introduction to C++ Introduction to C++ Week 7 Dr Alex Martin 2013 Slide 1 Introduction to C++ Introduction to C++ Week 7 Dr Alex Martin 2013 Slide 1 Introduction to Classes Classes as user-defined types We have seen that C++ provides a fairly large set of built-in types. e.g

More information

INTRODUCTION TO OBJECTIVE-C CSCI 4448/5448: OBJECT-ORIENTED ANALYSIS & DESIGN LECTURE 12 09/29/2011

INTRODUCTION TO OBJECTIVE-C CSCI 4448/5448: OBJECT-ORIENTED ANALYSIS & DESIGN LECTURE 12 09/29/2011 INTRODUCTION TO OBJECTIVE-C CSCI 4448/5448: OBJECT-ORIENTED ANALYSIS & DESIGN LECTURE 12 09/29/2011 1 Goals of the Lecture Present an introduction to Objective-C 2.0 Coverage of the language will be INCOMPLETE

More information

PROBLEMS (Cap. 4 - Istruzioni macchina)

PROBLEMS (Cap. 4 - Istruzioni macchina) 98 CHAPTER 2 MACHINE INSTRUCTIONS AND PROGRAMS PROBLEMS (Cap. 4 - Istruzioni macchina) 2.1 Represent the decimal values 5, 2, 14, 10, 26, 19, 51, and 43, as signed, 7-bit numbers in the following binary

More information

Bachelors of Computer Application Programming Principle & Algorithm (BCA-S102T)

Bachelors of Computer Application Programming Principle & Algorithm (BCA-S102T) Unit- I Introduction to c Language: C is a general-purpose computer programming language developed between 1969 and 1973 by Dennis Ritchie at the Bell Telephone Laboratories for use with the Unix operating

More information

Parameter Passing. Parameter Passing. Parameter Passing Modes in Fortran. Parameter Passing Modes in C

Parameter Passing. Parameter Passing. Parameter Passing Modes in Fortran. Parameter Passing Modes in C Parameter Passing In this set of notes you will learn about: Parameter passing modes Call by Call by reference Call by sharing Call by result Call by /result Call by name Subroutine closures as parameters

More information

Introduction to Java Applications. 2005 Pearson Education, Inc. All rights reserved.

Introduction to Java Applications. 2005 Pearson Education, Inc. All rights reserved. 1 2 Introduction to Java Applications 2.2 First Program in Java: Printing a Line of Text 2 Application Executes when you use the java command to launch the Java Virtual Machine (JVM) Sample program Displays

More information