Download presentation
Presentation is loading. Please wait.
Published bySherilyn Scott Modified over 9 years ago
1
STRUCTURE OF A C++ PROGRAM
2
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.
3
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.
4
CLIENT-SERVER MODEL
5
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" ;
6
Cascading of I/O Operators or Cout << "Sum=" << Sum << "," << "Average =" <<average << "In" ; The output will be Sum = 14, Average = 7
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);
8
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.
9
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.
10
OTHER OPERATORS IN C++ C++ has a rich set of operators. << insertion operator >> extraction operator :: scope Resolution operator :: * Pointer to member declarator
11
OTHER OPERATORS IN C++ Contd.. ->* Pointer to member operator.* Pointer to member operator delete Memory release operator endl Line feed operator
12
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.
13
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.
14
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
15
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.
16
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
17
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.
18
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"; }
19
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
20
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.
21
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.
22
Memory Management Operators Contd.. new - creates an object delete - destroys an already existing object General form of new operator : pointer-variable = new data-type;
23
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;
24
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);
25
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];
26
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
27
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.
28
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 ;
29
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;
30
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"; } ----
31
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.
32
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.
33
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'
34
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.
35
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
36
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
37
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.
38
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 }
39
Defining member functions Contd.. Function definition heading
40
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.
41
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; }
42
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.
43
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.
44
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();
45
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 () :
46
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.
47
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); };
48
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 }
49
NESTING OF MEMBER FUNCTIONS Contd.. void set :: display(void) { cout <<"Largest value =" <<largest()<<"\n"; main() { set A; A.input(); A.display(); }
50
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
51
PRIVATE MEMBER FUNCTION //.... Main program... // main() { item x; // create object x cout<<"\n object x"<<"\n"; x.getdata (100, 299.95); // call member function x.putdata(); item y; // create object y cout <<"\n object y"<<"\n"; y.get data (200, 175.50); y.putdata(); }
52
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.
53
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; }
54
PRIVATE MEMBER FUNCTION Contd.. Defining the member function within the class definition: void putdata (void) { cout <<number<<"\n"; cout <<cost<<"\n"; }
55
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"; } };
56
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); };
57
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; }
58
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"; }
59
Conceptual picture of objects belonging to the person class.
60
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.
61
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
62
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.
63
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
64
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; ----------- }
65
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;
66
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);
67
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.
68
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.
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.