STRUCTURE OF A C++ PROGRAM
It is a common practice to organize a program into three separate files. The class declarations are placed in a header file and the definitions of member functions go into another file.
STRUCTURE OF A C++ PROGRAM Contd.. This enables the programmer to separate the abstract specification of the interface (class definition) from the implementation details (member functions definition). Finally, the main program that uses the class is placed in a third file which "includes" the previous two files as well as any other file required.
CLIENT-SERVER MODEL
Cascading of I/O Operators Cout << "Sum=" << Sum << "In" ; The multiple use of << in one statement is called Cascading. e.g. Cout << "Sum = " << Sum <<"In" <<” Average="<<average << "In" ;
Cascading of I/O Operators or Cout << "Sum=" << Sum << "," << "Average =" <<average << "In" ; The output will be Sum = 14, Average = 7
Cascading of Input Operators Cin >> number 1 >> number 2; The values are assigned from left to right. e.g. if 10 and 20 are input, then number 1 = 10 number 2 = 20 The x becomes an alias of m after executing the statement f(m);
Cascading of Input Operators Such function calls are known as 'call by reference'. Since the variables x and m are aliases, when the function increments x, m is also incremented. The value of m becomes 20 after the function is executed.
Cascading of Input Operators Use : Call by reference permits the manipulations of objects by reference and eliminates the copying of object parameters back and forth.
OTHER OPERATORS IN C++ C++ has a rich set of operators. << insertion operator >> extraction operator :: scope Resolution operator :: * Pointer to member declarator
OTHER OPERATORS IN C++ Contd.. ->* Pointer to member operator.* Pointer to member operator delete Memory release operator endl Line feed operator
OTHER OPERATORS IN C++ Contd.. new Memory allocation operator setw Field width operator C++ also allows us to provide new defunctions to some of the built-in operators. We can give several meanings to an operator, depending upon the types of arguments used. This process is known as OPERATOR OVERLOADING.
SCOPE RESOLUTION OPERATOR :: Some variable name can be used to have different meanings in different blocks. The scope of the variable extends from the point of its declaration till the end of the block containing the declaration. A variable declared inside a block is said to be local to that block.
SCOPE RESOLUTION OPERATOR :: Contd { int x=10; } int x=1; x refers to two different memory locations { int x=10; { int x=1; } } Block2 Block1Block1
SCOPE RESOLUTION OPERATOR :: Contd.. Note : Inner Block hides and declaration of the same variable in an outer block & each declaration of x causes it to refer to a different data object.
SCOPE RESOLUTION OPERATOR :: Contd.. In C, the global version of a variable cannot be accessed from within the inner block. C++ resolves this problem by introducing a new operator :: called the Scope resolution operator. This can be used to uncover a hidden variable. :: variable name
SCOPE RESOLUTION OPERATOR :: Contd.. :: allows access to the global version of a variable e.g. :: count means the global version of the variable count and not the local variable count declared in that block.
SCOPE RESOLUTION OPERATOR :: Contd.. Example # include int m = 10; // global m mainl, { int m = 20; // n redeclared, local to main { int k = m; int m = 30; // m again, local to inner block cout <<"We are in inner block \ n"; cout <<"m = <<m<<"In"; }
SCOPE RESOLUTION OPERATOR :: Contd.. cout <<"We are in outer block \n"; cout <<"m =" << m << "\n"; cout <<":: m = "<<:: m <<"\n"; } We are in inner block We are in outer block k = 20 m = 20 m = 30 :: m = 10 :: m = 10
Member Deferencing Operators Operator Function :: To declare a pointer to a member of a class. - To access a member using an object name and a pointer to that member. -> To access a member using a pointer to the object and a pointer to that member.
Memory Management Operators C - malloc(), Calloc() free() - free dynamically allocated memory. C++ supports dynamic memory allocation using two unary operators new and delete that perform the task of allocating and freeing the memory in a better and easier way.
Memory Management Operators Contd.. new - creates an object delete - destroys an already existing object General form of new operator : pointer-variable = new data-type;
Memory Management Operators Contd.. The new operator allocates sufficient memory to hold a data object of type data-type and returns the address of the object. The data-type can be any valid data-type. The pointer-variable holds the address of the memory space allocated. e.g. p = new int; int *p = new int; or f = new float; float *f = new float;
Memory Management Operators Contd.. Using new operator to initialize memory : e.g. int *p = new int(25); float *f = new float (7.5); New can be used to create a memory space for any data type including user-defined types such as arrays, structures and classes. pointer-variable = new data-type (value);
Memory Management Operators Contd.. size specifies the number of elements in the array. int *p = new int [10]; int *p = new int [10]; creates a memory space for an array of 10 integers. pointer-variable = new data-type [size];
Memory Management Operators Contd.. p[0] - refers to first element p[1] - refers to second element etc. Declaring multi-dimensional arrays. array ptr = new int [3] [5] [4]; //legal
Memory Management Operators Contd.. array ptr = new int [ ] [5] [4]; // illegal array-ptr = new int [m] [5] [4]; // legal ~ first dimension may be a variable whose value is supplied at runtime. All others must be constants.
Delete Operator When a data object is no longer needed, it is destroyed to release the memory space for reuse. The general form of its use is : e.g. delete p; delete f; delete pointer-variable ;
Delete Operator Contd.. To free a dynamically allocated array: The size specifies the number of elements in the array to be freed. The problem with this form is that the programmer should remember the size of the array. Recent version. delete [size] pointer-variable;
Delete Operator Contd.. delete [ ] p; will delete the array pointed by p Check the memory allocation before using: p = new int; if (!p) { cout <<"allocation failed \n"; } ----
Delete Operator Contd.. The new operator has several advantages over the function malloc(). 1. It automatically computes the size of the data object. No need to use size of () operator. 2. It automatically returns the correct pointer type, therefore no need of using type cast.
Delete Operator Contd.. 3. It is possible to initialize the object while creating the memory space. 4. Like any other operator, new and delete can be overloaded.
MANIPULATORS Manipulators are operators that are used to format the data display. endl & Setw endl manipulator when used in an object statement, causes a linefeed to be inserted ~ to '\n'
MANIPULATORS Contd.. cout <<"m="<<m<<endl cout <<"n"<<n<<endl Setw manipulator can be used to specify a common field width for all the numbers and force them to be printed right-justified.
MANIPULATORS Contd.. main () { int Basic = 950; int total = 1045; cout << Setw(10)<<"Basic"<< setw(10)<<Basic << and cout << setw(10)<<"Allowance"<< setw(10) <<allowance<<and } Basic 950 total 1045
Type Cast Operator C++ permits explicit type conversion of variables expressions using the type cast operator. (type-name) expression // c notation type-name (expression) // C++ notation e.g. average = Sum / (float)i; average = Sum / float(i); similar to function
Defining member functions Member functions can be defined in two places : ~ Outside the class definition ~ Inside the class definition An important difference between a member function and a normal function is that a member function incorporates a membership "identity label" in the header. This 'label' tells the compiler which Class the function belongs to.
Defining member functions Contd.. General form of a member function definition is : Member-function definition is almost similar to the regular function definition. return-type class-name :: function-name (arguments declarator) { Function body }
Defining member functions Contd.. Function definition heading
The membership label Class-name : Tells the compiler that the function-name belongs to the class Class-name. That is, the scope of the function is restricted to the class-name specified in the header-line. The SRO-Scope Resolution Operator tells that the member functions belong to the class person.
The membership label Note: You can use the same data member names and member function names in a different class belonging to the same program. Example: void item :: get data (int a, float b) { number = a; cost = b; }
The membership label void item :: put data (void) { cout <<"Number:"<<number<<"\n"; cout <<"Cost :" <<cost<<"\n"; } Since these functions donot return any value, their return-type is void.
Special characteristics of Member functions 1) Several different classes can use the same function name. The 'membership label' will resolve their scope. (2) Member functions can access the private data of the class. A non-member function cannot do so. (However, an exception to this rule is a 'friend' function) 3) A member function can call another member function directly, without using the dot operator.
Special characteristics of Member functions void main (void) { person p1, p2; p1. set-person-data ("Bill", 40, 170.5); cout <<"Enter the following data :"<<\n"; p2. get-person-data(); cout <<"\n"; cout <<"Data about the first person: \n"; p1. Show-person-data();
Special characteristics of Member functions cout <<"\n"; cout <<"Data about the second person :\n"; p2. Show-person-data(); } Note: We cannot write the following type of statements in the main () :
Special characteristics of Member functions p1. age = 40; p2 height = 169.5; Strcpy (p1.name, "George"); :: variables age, height and name are declared private. Had they been declared public, the above statements would have been allowed.... the only way to reach private class member data is through public member functions that access the data member.
NESTING OF MEMBER FUNCTIONS A member function can be called using its name outside another member function of the same class. # include Class set { int m, n; public void input(void); void display(void); int largest (void); };
NESTING OF MEMBER FUNCTIONS Contd.. int set :: largest(void) { if (m>= n) return(m); else return(n); } void set :: input(void) { cout <<"Input values of m and n"<<"\n"; cin >>m>>n }
NESTING OF MEMBER FUNCTIONS Contd.. void set :: display(void) { cout <<"Largest value =" <<largest()<<"\n"; main() { set A; A.input(); A.display(); }
PRIVATE MEMBER FUNCTION A private member function can only be called by another function that is a member of that Class. // Member Function definition // Example void item :: getdata (int a, float b) // use membership label { number = a; // private variables cost = b; // directly used
PRIVATE MEMBER FUNCTION //.... Main program... // main() { item x; // create object x cout<<"\n object x"<<"\n"; x.getdata (100, ); // call member function x.putdata(); item y; // create object y cout <<"\n object y"<<"\n"; y.get data (200, ); y.putdata(); }
PRIVATE MEMBER FUNCTION Contd.. Note: The use of statement number = a; in the function getdata(). This shows that the member functions can have direct access to private data items. The member function putdata() has been defined inside the class &.-. behaves like an inline function. This function displays the values of the private variable number and cost.
PRIVATE MEMBER FUNCTION Contd.. Defining the member function within the class definition: Class item { int number; float cost; public: void getdata (int a, float b); { number = a; cost = b; }
PRIVATE MEMBER FUNCTION Contd.. Defining the member function within the class definition: void putdata (void) { cout <<number<<"\n"; cout <<cost<<"\n"; }
A C++ program with class # include Class item // class declaration { int number; // private by default float cost; public: void getdata(int a, float b); //prototype declaration void putdata(void) //function definition { cout <<number<<"\n"; cout <<cost :<<cost<<"\n"; } };
A C++ program with class Complete C++ program that uses object of a Class # include Class person {private: char name [20]; int age; double height; public : void get-person-data(void); void set-person-data(char*string, int a, double h); void show-person-data(void); };
A C++ program with class C++ program that uses object of a Class Contd.. void person :: get-person-data(void) { cout <<"Enter the name of the person:"; cin get(name,20); cout <<"Enter the age of the person :"; cin >>age, cout <<"Enter the height of the person:"; cin >> height; }
A C++ program with class C++ program that uses object of a Class Contd.. void person :: Set-person-data (char*string, int a, double h) { Stepy (name, string); age = a; height = h; } void person :: Show-person-data(void) } cout <<"Name of the person:"<<name<<"\n"; cout <<"Age of the person :"<<age<<"years\n"; cout <<"Height of the person:"<<height<<"cm\n"; }
Conceptual picture of objects belonging to the person class.
REFERENCE VARIABLES IN C++ A reference variable must be initialized at the time of declaration. This establishes the correspondence between the reference and the data object that it names. Note that the initialization of a reference variable is completely different from assignment to it.
REFERENCE VARIABLES IN C++ C++ assigns additional meaning to the symbol &. Here, & is not an address operator. float & means reference to float. int n[10]; int &x = n[10]; // x is alias for n[10] char &a = "\n"; // initialize reference to a literal
REFERENCE VARIABLES IN C++ Contd.. The variable x is an alternative to the array element n[10]. The variable a is initialized to newline constitutes. This creates a reference to the otherwise unknown location where the newline constitutes \n is stored.
REFERENCE VARIABLES IN C++ Contd.. The following references are also allowed : int x; int *p = &x; int &m = *p; int &n = 50; creates an object with value 50 and name n. causes m to refer to x which is pointed to by the pointer p
REFERENCE VARIABLES IN C++ Contd.. A major application of reference variables is in passing arguments to functions. void f(int &x) // uses reference { x = x+10; // x is incremented; so also m } main () { int m = 10; }
REFERENCE VARIABLES IN C++ Contd.. A major application of reference variables is in passing arguments to functions. When the function call f(m) is executed, the following initialization occurs int &x = m;
CALL BY REFERENCE FUNCTIONS IN C++ Function Prototype is a declaration statement in the calling program and is of the following form : type function-name (argument list); The argument list contains the types and names of arguments that must be passed to the function. float volume (int x, float y, float z);
CALL BY REFERENCE FUNCTIONS IN C++ Note: The variable names in the argument list of prototype act as placeholders &. : ; of names are used, they don't have to match the names used in the function call or function definition.
CALL BY REFERENCE required when we like to alter the values of original variables in the calling program. e.g. Bubble sort, we compare two adjacent elements in the list and exchange if the first element is greaterthan second - which is not possible if call-by-value method is used.