STRUCTURE OF A C++ PROGRAM

68
STRUCTURE OF A C++ PROGRAM

description

STRUCTURE OF A C++ PROGRAM. 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. - PowerPoint PPT Presentation

Transcript of STRUCTURE OF A C++ PROGRAM

Page 1: STRUCTURE OF A C++ PROGRAM

STRUCTURE OF A C++ PROGRAM

Page 2: STRUCTURE OF A C++ PROGRAM

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.

Page 3: STRUCTURE OF A C++ PROGRAM

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.

Page 4: STRUCTURE OF A C++ PROGRAM

CLIENT-SERVER MODEL

Page 5: STRUCTURE OF A C++ PROGRAM

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" ;

Page 6: STRUCTURE OF A C++ PROGRAM

Cascading of I/O Operators

or Cout << "Sum=" << Sum << "," << "Average =" <<average << "In" ; The output will be Sum = 14, Average = 7

Page 7: STRUCTURE OF A C++ PROGRAM

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);

Page 8: STRUCTURE OF A C++ PROGRAM

Cascading of Input OperatorsSuch 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.

Page 9: STRUCTURE OF A C++ PROGRAM

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.

Page 10: STRUCTURE OF A C++ PROGRAM

OTHER OPERATORS IN C++

C++ has a rich set of operators. << insertion operator >> extraction operator :: scope Resolution operator :: * Pointer to member declarator

Page 11: STRUCTURE OF A C++ PROGRAM

OTHER OPERATORS IN C++ Contd..

->* Pointer to member operator .* Pointer to member operator delete Memory release operator endl Line feed operator

Page 12: STRUCTURE OF A C++ PROGRAM

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 meaningsto an operator, depending upon the types of argumentsused. This process is known as

OPERATOR OVERLOADING.

Page 13: STRUCTURE OF A C++ PROGRAM

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 ofthe block containing the declaration.

•A variable declared inside a block is said to be local to that block.

Page 14: STRUCTURE OF A C++ PROGRAM

SCOPE RESOLUTION OPERATOR :: Contd..

------------{int x=10;}------------int x=1;------------x refers to two differentmemory locations.

-------{int x=10;------------{int x=1;------------}------}

Block2

Block1

Page 15: STRUCTURE OF A C++ PROGRAM

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.

Page 16: STRUCTURE OF A C++ PROGRAM

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

Page 17: STRUCTURE OF A C++ PROGRAM

SCOPE RESOLUTION OPERATOR :: Contd..

:: allows access to the global version of a variable e.g. :: count means the global version of the variablecount and not the local variable count declaredin that block.

Page 18: STRUCTURE OF A C++ PROGRAM

SCOPE RESOLUTION OPERATOR :: Contd..

Example # include <io stream.h> 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"; }

Page 19: STRUCTURE OF A C++ PROGRAM

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

Page 20: STRUCTURE OF A C++ PROGRAM

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.

Page 21: STRUCTURE OF A C++ PROGRAM

Memory Management Operators

C - malloc(), Calloc()

free() - free dynamically allocated memory. C++ supports dynamic memory allocation using two unary operators new and delete that performthe task of allocating and freeing the memory in a better and easier way.

Page 22: STRUCTURE OF A C++ PROGRAM

Memory Management Operators Contd..

new - creates an object delete - destroys an already existing

object General form of new operator :

pointer-variable = new data-type;

Page 23: STRUCTURE OF A C++ PROGRAM

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;

Page 24: STRUCTURE OF A C++ PROGRAM

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);

Page 25: STRUCTURE OF A C++ PROGRAM

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];

Page 26: STRUCTURE OF A C++ PROGRAM

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

Page 27: STRUCTURE OF A C++ PROGRAM

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.

Page 28: STRUCTURE OF A C++ PROGRAM

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 ;

Page 29: STRUCTURE OF A C++ PROGRAM

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;

Page 30: STRUCTURE OF A C++ PROGRAM

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"; } ---- ----

Page 31: STRUCTURE OF A C++ PROGRAM

Delete Operator Contd.. The new operator has several advantages over thefunction 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.

Page 32: STRUCTURE OF A C++ PROGRAM

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.

Page 33: STRUCTURE OF A C++ PROGRAM

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'

Page 34: STRUCTURE OF A C++ PROGRAM

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.

Page 35: STRUCTURE OF A C++ PROGRAM

MANIPULATORS Contd.. main () { int Basic = 950; int total = 1045;

cout << Setw(10)<<"Basic"<< setw(10)<<Basic<< andcout << setw(10)<<"Allowance"<< setw(10)<<allowance<<and

} Basic 950 total 1045

Page 36: STRUCTURE OF A C++ PROGRAM

Type Cast Operator

C++ permits explicit type conversion ofvariables expressions using the type cast operator.

(type-name) expression // c notationtype-name (expression) // C++ notation

e.g. average = Sum / (float)i;average = Sum / float(i);

similar to function

Page 37: STRUCTURE OF A C++ PROGRAM

Defining member functionsMember 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.

Page 38: STRUCTURE OF A C++ PROGRAM

Defining member functions Contd..

General form of a member function definition is :

Member-function definition is almost similar to theregular function definition.

return-type class-name :: function-name (arguments declarator)

{ Function body

}

Page 39: STRUCTURE OF A C++ PROGRAM

Defining member functions Contd..Function definition heading

Page 40: STRUCTURE OF A C++ PROGRAM

The membership label

Class-name :

Tells the compiler that the function-namebelongs 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.

Page 41: STRUCTURE OF A C++ PROGRAM

The membership labelNote: 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; }

Page 42: STRUCTURE OF A C++ PROGRAM

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.

Page 43: STRUCTURE OF A C++ PROGRAM

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.

Page 44: STRUCTURE OF A C++ PROGRAM

Special characteristics of Member functionsvoid 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();

Page 45: STRUCTURE OF A C++ PROGRAM

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 () :

Page 46: STRUCTURE OF A C++ PROGRAM

Special characteristics of Member functionsp1. 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 datais through public member functions that access thedata member.

Page 47: STRUCTURE OF A C++ PROGRAM

NESTING OF MEMBER FUNCTIONSA member function can be called using its name outside another member function of the same class.# include <iostream.h> Class set { int m, n; public void input(void); void display(void); int largest (void); };

Page 48: STRUCTURE OF A C++ PROGRAM

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 }

Page 49: STRUCTURE OF A C++ PROGRAM

NESTING OF MEMBER FUNCTIONS Contd..

void set :: display(void) { cout <<"Largest value =" <<largest()<<"\n"; main() { set A; A.input(); A.display(); }

Page 50: STRUCTURE OF A C++ PROGRAM

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

Page 51: STRUCTURE OF A C++ PROGRAM

PRIVATE MEMBER FUNCTION

// .... Main program ... // main() { item x; // create object xcout<<"\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(); }

Page 52: STRUCTURE OF A C++ PROGRAM

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.

Page 53: STRUCTURE OF A C++ PROGRAM

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; }

Page 54: STRUCTURE OF A C++ PROGRAM

PRIVATE MEMBER FUNCTION Contd..

Defining the member function within the class definition:

void putdata (void) { cout <<number<<"\n"; cout <<cost<<"\n"; }

Page 55: STRUCTURE OF A C++ PROGRAM

A C++ program with class # include <iostream.4> 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";} };

Page 56: STRUCTURE OF A C++ PROGRAM

A C++ program with classComplete C++ program that uses object of a Class

# include <iostream.4># include <string.4>

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); };

Page 57: STRUCTURE OF A C++ PROGRAM

A C++ program with classC++ 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; }

Page 58: STRUCTURE OF A C++ PROGRAM

A C++ program with classC++ 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"; }

Page 59: STRUCTURE OF A C++ PROGRAM

Conceptual picture of objects belonging to the person class.

Page 60: STRUCTURE OF A C++ PROGRAM

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.

Page 61: STRUCTURE OF A C++ PROGRAM

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

Page 62: STRUCTURE OF A C++ PROGRAM

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.

Page 63: STRUCTURE OF A C++ PROGRAM

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

Page 64: STRUCTURE OF A C++ PROGRAM

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;

----------- ----------- }

Page 65: STRUCTURE OF A C++ PROGRAM

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;

Page 66: STRUCTURE OF A C++ PROGRAM

CALL BY REFERENCEFUNCTIONS 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);

Page 67: STRUCTURE OF A C++ PROGRAM

CALL BY REFERENCEFUNCTIONS 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.

Page 68: STRUCTURE OF A C++ PROGRAM

CALL BY REFERENCErequired 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.