module 1

46
MODULE 1 C o nt e nt s 1. Fundamentals of object oriented concepts 2. Designing an object oriented system 3. C++ program structure 4. C++ enhancements to C 5. References 1

Upload: akash-raj

Post on 21-Jul-2016

213 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: MODULE 1

MODULE 1

C o nt e nt s 1. Fundamentals of object oriented concepts

2. Designing an object oriented system

3. C++ program structure

4. C++ enhancements to C

5. References

1

Page 2: MODULE 1

Procedure Oriented Programming

Conventional programming, using high level languages such as COBOL, FORTRAN,and C, is commonly known as procedure-oriented programming(POP). In POP the main program is divided into a number of functions. A typical program structure for procedure oriented programming is shown in figure.

In a multi-function program many important data items are placed as global so that they may be accessed by all the functions. Each function may have its own local data. Global data are vulnerable to an inadvertent change by a function. In a large program it is very difficult to identify what data is used by which function.

Another drawback of POP is that it does not model real world entities well. This is because functions are action-oriented and do not really correspond to the elements of the problem. POP employs top-down approach in program design

Object-Oriented Programming

OOP decomposes a problem into a number of entities called objects and then build data and functions around these objects. The organization of data and functions in object-oriented programs is shown in figure.

2

Page 3: MODULE 1

Functions that operate on data of an object are tied together in that object. Data is hidden and cannot be accessed by external functions. Objects may communicate with each other through functions. The data of an object can be accessed only by the fuctions associated with that object. However, functions of one object can access the functions of other objects. New data and functions can be added whenever necessary.

OOP follows bottom-up approach in program design.

Fundamentals of Object oriented design

Objects

Classes

Data Abstraction

Encapsulation

Inheritance

Polymorphism

3

Page 4: MODULE 1

Objects

Objects are the basic run-time entities in object-oriented design. E.g.:- a person, a place, a bank account.

An object is an instantiation of a class. In terms of variables, a class would be the type, and an object would be the variable.

Figure shows the two ways of representing an object.

During execution, the objects interact by sending messages. For example, if “customer” and “account” are two objects in a program, then the customer object may send a message to the account object requesting for the bank balance. Each object contains data, and code to manipulate the data. Objects can interact without having to know details of each others data or code.

ClassesA class is a collection of data and its associated functions referenced under one name. It

is actually a collection of objects of the same type. i.e, objects are variables of the type class.

E.g.:- fruit is a class apple, orange etc are objects of the class fruit

fruit mango

will create an object mango belonging to the class fruit.

A class is an expanded concept of a structure: instead of holding only data, it can hold both data and functions. In programming language class is a user defined data type that behave like a built in data type. Here we must use the keyword public to access the class member and member function outside of the class because by default class member and member functions are private.

4

Average

Display

STUDENT

TotalObject: STUDENT

DATANameDate-of-birthMarks…………

FUNCTIONSTotal AverageDisplay

Page 5: MODULE 1

Structure: Structure is collection of heterogeneous data type. In structure all it's member and member functions are public. It can accessible anywhere in the main function. By default structure members are public. 

class X {

// private by default int a;

public:

// public member function int f() { return a = 5; };};

struct Y {

// public by default int f() { return a = 5; };

private:

// private data member int a;};

Encapsulation

The wrapping up of data and function into a single unit (called class) is known as encapsulation. Data and encapsulation is the most striking feature of a class. The data is not accessible to the outside world, and only those functions which are wrapped in the class can access it. These functions provide the interface between the object’s data and the program. This insulation of the data from direct access by the program is called data hiding or information hiding.

Data Abstraction

Abstraction refers to the act of representing essential features without including the background details or explanation. Classes use the concept of abstraction and are defined as a list of abstract attributes such as size, wait, and cost, and function operate on these attributes. They encapsulate all the essential properties of the object that are to be created. The attributes are some time called data members because they hold information. The functions that operate on these data are sometimes called methods or member function.

Since the classes use the concept of data abstraction, they are known as Abstract Data Types (ADT).

5

Page 6: MODULE 1

Inheritance

Inheritance is the process by which objects of one class acquired the properties of objects of another classes. It supports the concept of hierarchical classification. For example, the bird, ‘robin’ is a part of class ‘flying bird’ which is again a part of the class ‘bird’. The principal behind this sort of division is that each derived class shares common characteristics with the class from which it is derived as illustrated in figure.

Property inheritance

BirdsAttributesFeathersLay eggs

Flying bird

Attributes.................………………

Attributes………………..……………….

Attributes……………………………….

Attributes………………………………

Attributes………………………………

Attributes……………….……………….

Nonflying bird

Parrot Peacock Penguin Kiwi

In OOP, the concept of inheritance provides the idea of reusability. This means that we can add additional features to an existing class without modifying it. This is possible by deriving a new class from the existing one. The new class will have the combined feature of both the classes. The real appeal and power of the inheritance mechanism is that it allows the programmer to reuse a class.

Polymorphism

Polymorphism is the ability to take more than one form. An operation may exhibit different behavior in different instances. The behavior depends upon the types of data used in the operation. For example, consider the operation of addition. For two numbers, the operation will generate a sum. If the operands are strings, then the operation would produce a third string by concatenation. The process of making an operator to exhibit different behaviors in different instances is known as operator overloading.

E.g. :- operator +case 1 :- 3 + 4 = 7case 2 :- “abc” + “xyz” = “abcxyz”

6

Page 7: MODULE 1

Figure illustrates that a single function name can be used to handle different number and different types of argument. This is something similar to a particular word having several different meanings depending upon the context. Using a single function name to perform different type of task is known as function overloading.

C l a s s h i e r a rc h i e s A class that is inherited is referred to as a base class. The class that does

the inheriting is called the derived class.1. Single inheritance: Only one base class and one derived class.

A

B

2. Multilevel inheritance:

A

B

7

C

Page 8: MODULE 1

3. Multiple inheritance:

A B

C

4. Hierarchical Inheritance: A

B C

5 . Hybrid inheritance: Combination of more than one type of inheritance

A

B C

D

D e s ig n i n g an O b j ec t - o r i e n t e d s y s t e m

We shall use the following approach in designing the system:

• Identify the classes

• Assign attributes and behavior

• Find relationships between the classes

• Arrange the classes into hierarchies

8

Page 9: MODULE 1

I dent ifying c las ses:

One way to identify potential classes for a system is to look for nouns in the problem description. It is easier to identify classes if physical entities are part of the problem description. Thus a problem involving aero planes and passengers would suggest two obvious physical entities. Other potential classes that need to be considered are ones to represent events and interactions. For instance a transaction class may be appropriate in a bank system and a command class may be appropriate for actions performed by a user.

Ass ig ning att r ibut es and be ha vio r

Now we need to consider the responsibilities of the classes we have identified. We have to decide what information each class will maintain, i.e. what its attributes will be, and we have to decide what operations are performed on it or by it. As part of this process, we need to consider what role the class plays in relation to the whole system.

If one class becomes very large in comparison to all the others, i.e. it is accepting an unfair share of responsibilities, so it may be appropriate to split it into further classes. We need to ensure balance of responsibility amongst classes. In assigning responsibilities, we should also look for repetition amongst classes as this may suggest further abstraction using class hierarchies. Finally, if a class has no responsibilities assigned to it, then it should be discarded.

Having identified responsibilities for classes, this leads us to modeling the behavior of a class, which means we can identify methods that are required to perform the responsibilities. Parameters and return types for methods can be left until later in the design process.

F ind ing r e lat io ns hip bet ween c las ses

We need to look at relationships between classes, because a system is built upon cooperation between classes, although some classes may exist in isolation. Association represents relationship among classes. The most common relationships between classes are:

• Use(client-server association)• Containment (“has-a”)• Inheritance (“is-a-kind-of”)

In Client-server (consumer-producer) association, one object requests the service of another object. The object that makes the request is consumer or client. The object that receives request and provide service is producer or server.

In containment (aggregation), all objects, except most basic ones, are composed of and may contain other objects. Eg. Spread sheet is an object composed of cells,and cells are objects that may contain text, formulas etc. A car is an aggregation of engine, seat, wheels, and other objects.

9

Page 10: MODULE 1

Arr a ng ing c la sse s int o hier ar chy

This stage is an extension of the first design step where we identified potential classes for a system. However, steps two and three have furnished us with further information that will help us to identify hierarchies. By assigning attributes and behaviors to classes in step 2, we will develop a closer idea of their similarities and differences. By identifying the relationships of step 3, we see which classes need to incorporate the functionality of others.

A first look at C++

C++ is an object-oriented programming language. It was developed by Bjarne Stroustrup at AT&T Bell Laboratories in Murray Hill, New Jersey, USA, in the early 1980’s. Stroustrup, an admirer of Simula67 and a strong supporter of C, wanted to combine the best of both the languages and create a more powerful language that could support object-oriented programming features and still retain the power and elegance of C. The result was C++. Therefore, C++ is an extension of C with a major addition of the class construct feature of Simula67. Since the class was a major addition to the original C language, Stroustrup initially called the new language ‘C with classes’. However, later in 1983, the name was changed to C++. The idea of C++ comes from the C increment operator ++, thereby suggesting that C++ is an augmented version of C.

C+ + is a superset of C. Almost all C programs are also C++ programs. However, there are a few minor differences that will prevent a C program to run under C++ compiler.

The most important facilities that C++ adds on to C are classes, inheritance, function overloading and operator overloading. These features enable creating of abstract data types, inherit properties from existing data types and support polymorphism, thereby making C++ a truly object-oriented language.

A Simple C++ program

#include<iostream.h>

int main()

{

cout<<”Welcome”;

return 0;

}

#include <iostream.h>

Lines beginning with a hash sign (#) are directives for the preprocessor. They are not regular code lines with expressions but indications for the compiler's preprocessor. In this case the directive #include <iostream.h> tells the preprocessor to include the iostream standard file. This specific file (iostream.h) includes the declarations of the

10

Page 11: MODULE 1

basic standard input-output library in C++, and it is included because its functionality is going to be used later in the program.int main ()

This line corresponds to the beginning of the definition of the main function. The main function is the point by where all C++ programs start their execution, independently of its location within the source code. It does not matter whether there are other functions with other names defined before or after it – the instructions contained within this function's definition will always be the first ones to be executed in any C++ program. For that same reason, it is essential that all C++ programs have a main function.cout << "Welcome”;

cout represents the standard output stream in C++, and the meaning of the entire

statement is to insert (or put to operator) a sequence of characters (in this case the Welcome sequence of characters) into the standard output stream (which usually is the screen).Notice that the statement ends with a semicolon character (;). This character is used to mark the end of the statement and in fact it must be included at the end of all expression statements in all C++ programs.return 0;

The return statement causes the main function to finish. A return code of 0 for the main function is generally interpreted as the program worked as expected without any errors during its execution. This is the most usual way to end a C++ program.

Program to add two numbers

#include<iostream.h>#include<conio.h>void main(){

clrscr();int a, b, sum;cout<<“enter 2 numbers”;cin>>a;cin>>b;sum= a+b;cout<<“the sum =“<<sum;getch();

}Input operator – cin>>

The identifier cin is a predefined object in C++ that corresponds to standard i/p stream (keyboard). The operator >> is known as extraction or get from operator. It extracts the value from the keyboard and assigns it to the variable on its right.

Cascading of I/O operatorsThe multiple use of << or >> in one statement is called cascading of I/O operators

E.g. :-cout<<“sum is “<<sum;

11

Page 12: MODULE 1

cin>>a>>b;C++ enhancements to C

Default Function ArgumentsA function can be called without specifying all its arguments. In such cases, the

function assigns a default value to the parameter which does not have a matching argument in function call. Default values are specified during function declaration. E.g. :-

float amount(float principal, int period, float rate=0.15);Suppose the function call is

value = amount(5000,7);

Here one argument is missing and hence the default value is used for the argument rate.value = amount(5000,5,0.12);

passes an explicit value of 0.12 to rate.An argument can be assigned a default value only if all the arguments on its

right have default values. int add(int i, int j=5, int k=10); legalint add(int i=5, int j, int k=10); illegalint add(int i, int j, int k=10); legalint add(int i=10, int j, int k); illegal

Placement of variable declarationsIn C all variables must be declared before they are used in executable statements

(at the beginning of scope). But C++ allows the declaration of a variable anywhere in the scope. This means that a variable can be declared right at the place of its first use.

#include<iostream.h>#include<conio.h>void main(){

clrscr();int n, a[100],sum;cout<<“enter the limit”;cin>>n;cout<<“enter the numbers”;

for(i=0; i<n; i++){

cin>>a[i];sum= sum+a[i];

}float avg = sum/n;cout<<“Sum=“<<sum;cout<<“Avg=“<<avg;getch();

}

12

Page 13: MODULE 1

Variables in both C and C++ can be declared globally (outside function definitions) and locally (inside a function or block). The C++ standard differs from C standard as follows:

Local variables in C should be declared immediately after the opening braces ({)

that indicates the beginning of a function or block. Local variables in C++ can be declared anywhere within a function or block

as long as they are declared before being used.Scope Resolution Operator

The scope of a 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. A variable declared outside all the blocks is said to be global variable.C++ provides the scope resolution operator (::). This can be used to access

global variables that have same name as of local variables. The following code demonstrates the use of scope resolution operator:

13

Page 14: MODULE 1

#include<iostream.h>#include<conio.h>int m=10;void main(){

clrscr();int m=20;{

int k=m;int m=30;cout<<“inner block”;cout<<“k=“<<k;cout<<“m=“<<m;cout<<“::m=“<<::m;

}

cout<<“outer block”;cout<<“m=“<<m;cout<<“ ::m = “<< ::m;getch()}

Output

14

Inner block k=20 m=30::m=10

Outer block m=20::m=10

Page 15: MODULE 1

“const” qualifier

The qualifier const is used to create symbolic constants in C++.E.g. :-

const int n=100;int a[n]; // invalid in C

The qualifier const allows us to create typed constants instead of having #define that creates constants that have no type information.If we use const qualifier alone it defaults int.

const size = 100; meansconst int size = 100;

C++ requires const to be initializedThe scope of a const value is local to the file where it is declared.To give a const value an external linkage we must explicitly define it as extern in C++.

extern const total = 1000; Function overloading

The use of the same function name to create functions that perform a variety of different tasks - Function overloading. We can define a family of functions with one function name but with different argument lists. The correct function to be invoked is determined by checking the number and type of the arguments and not on function type.

E.g. :- overloaded add() functionint add(int a, int b); //prototype 1int add(int a, int b, int c); //prototype 2double add(double x, double y); //prototype 3double add(int p, double q); //prototype 4double add(double p, int q); //prototype 5 // function callscout<<add(5,10); // uses prototype 1cout<<add(15,10.0); // uses prototype 4cout<<add(12.5,7.5); // uses prototype 3cout<<add(5,10,15); // uses prototype 2cout<<add(0.75,10); // uses prototype 5

A function call matches the prototype having the same number and type of arguments and then calls the appropriate function for execution.

The function selection involves the following steps.1. The compiler first tries to find an exact match. 2. If an exact match is not found, the compiler uses integral promotions to the actual

arguments.char to intfloat to double

3. When either of them fails, the compiler tries to use the built-in-conversions to actual argumentsIf the conversion is possible to have a multiple match then the compiler will generate an error message. Suppose we use the following two functions:

15

Page 16: MODULE 1

long square(long n);double square(double x);

A function call such assquare(10)

will cause an error because int argument can be converted to either long or double thereby creating ambiguous situations

4. If all the steps fail then the compiler will try the user-defined conversions in combination with integral promotions and built in conversions

#include <iostream.h> void print(int i) {

cout << " Here is int " << i << endl; } void print(double f) {

cout << " Here is float " << f << endl; } void print(char c) {

cout << " Here is char" << c << endl; } void main() {

print(10); print(10.10); print(“X");

}

Inline functionsAn inline function is a function that can be expanded in line when it is invoked. The

compiler replaces the function call with the function code.Inline functions are defined as follows.

inline function-header{

function body}

E.g.:-inline double cube(double a){

return(a*a*a);}

The above function can be invoked by statements likec = cube(3.0);d = cube(2.5+1.5);

16

Page 17: MODULE 1

All inline functions must be defined before they are called. The speed benefits of inline functions diminish as the function grows in size. Usually, the functions are made inline when they are small enough to be defined in one or two lines.

E.g. inline double cube( double a) { return (a*a*a);}

The inline keyword merely sends a request, not a command, to the compiler. The compiler may ignore the request if the function definition is too long or too complicated.

Situations where inline functions does not work For functions returning values , if a loop, a switch, or a goto exists. For functions not returning values, if a return statement exists. If functions contain static variables. If inline functions are recursive.

References

References as AliasesA reference variable provides an alias (alternative name) for a previously defined

variable. A reference variable is created as follows:data-type & ref-name = var-name;

For e.g. , if we make the variable sum a reference to the variable total, then sum and total can be used interchangeably to represent that variable.

float total = 100;float & sum = total;

sum is the alternative name declared to represent the variable total. Both variables refer to the same data object in the memory.

The statement total = total + 10;will change the value of both total and sum to 110. A reference variable must be initialized at the time of declaration. C++ assigns an additional meaning to &. Here & is not an address operator.

int n[10];int & x = n[10]; // x is an alias of n[10]char & a = ‘ \n ’; // initialize reference to a literal

The following references are also allowed:int x;

int *p = &x;int & m = *p; int & n = 50;

References as function argumentsA major application of reference variables is in passing arguments to functions.

void f (int & x) // uses reference

17

Page 18: MODULE 1

{x = x + 10; // x is incremented; so also m}void main(){int m = 10;f(m); // function call………………}

When f(m) is executed, the following initialization occurs.int & x = m;

Thus x becomes an alias for m after executing f(m). Such function calls are called call by reference. In C we accomplish this using pointers and dereferencing technique.

A function can also return a reference.

int & max(int &x, int &y){

if(x>y)return x;

elsereturn y;

} The function returns a reference to x or y and not the values. This means the function call max(a,b) can appear on the left-hand side of an assignment

max(a, b) = -1;is legal and assigns -1 to a if it is larger, otherwise -1 to b.

As a function can be created to return a value of a primitive type, a function can also be defined to return a reference to a primitive type. When declaring such a function, you must indicate that it is returning a reference by preceding it with the ‘&’ operator. Here is an example:

#include <iostream.h>double & GetWeeklyHours()

{double h = 46.50;double &hours = h;return hours;

}int main(){

double hours = GetWeeklyHours();cout << "Weekly Hours: " << hours << endl;return 0;

}This would produce: Weekly Hours: 46.5

Benefits of OOP

18

Page 19: MODULE 1

OOP offers several benefits to both the program designer and the user. Object-Orientation contributes to the solution of many problems associated with the development and quality of software products. The new technology promises greater programmer productivity, better quality of software and lesser maintenance cost. The principal advantages are:

• Through inheritance, we can eliminate redundant code extend the use of existing classes. • We can build programs from the standard working modules that communicate with one

another, rather than having to start writing the code from start. This leads to saving of development time and higher productivity.

• The principle of data hiding helps the programmer to build secure program that can not be invaded by code in other parts of a programs.

• It is possible to have multiple instances of an object to co-exist without any interference. • It is possible to map object in the problem domain to those in the program. • It is easy to partition the work in a project based on objects. • The data-centered design approach enables us to capture more detail of a model can

implemental form. • Object-oriented system can be easily upgraded from small to large system. • Message passing techniques for communication between objects makes to interface

descriptions with external systems much simpler. • Software complexity can be easily managed.

Application of OOP The most popular application of object-oriented programming, up to now, has been in

the area of user interface design such as window. Hundreds of windowing systems have been developed, using the OOP techniques.

Real-business system are often much more complex and contain many more objects with complicated attributes and method. OOP is useful in these types of application because it can simplify a complex problem. The promising areas of application of OOP include:

• Real-time system • Simulation and modeling • Object-oriented data bases • Hypertext, Hypermedia, and expertext • AI and expert systems • Neural networks and parallel programming • Decision support and office automation systems • CIM/CAM/CAD systems

Static Data Member: It is generally used to store value common to the whole class. The static data member differs from an ordinary data member in the following ways :

(i) Only a single copy of the static data member is used by all the objects. (ii) It can be used within the class but its lifetime is the whole program. For making a data member static, we require :

(a) Declare it within the class. (b) Define it outside the class.

19

Page 20: MODULE 1

For example Class student { Static int count; //declaration within class ----------------- ----------------- ----------------- };

The static data member is defined outside the class as : int student :: count; //definition outside class

The definition outside the class is a must. We can also initialize the static data member at the time of its definition as:

int student :: count = 0; If we define three objects as : sudent obj1, obj2, obj3;

Advantages & Disadvantages of Inline functionsInline function is the optimization technique used by the compilers. One can simply prepend inline keyword to function prototype to make a function inline. Inline function instruct compiler to insert complete body of the function wherever that function got used in code.

Advantages :- 1) It does not require function calling overhead.2) It also save overhead of variables push/pop on the stack, while function calling.3) It also save overhead of return call from a function.4) It increases locality of reference by utilizing instruction cache.5) After in-lining compiler can also apply intraprocedural optmization if specified. This is the most important one, in this way compiler can now focus on dead code elimination, can give more stress on branch prediction, induction variable elimination etc..

Disadvantages :-1) May increase function size so that it may not fit on the cache, causing lots of cahce miss.2) After in-lining function if variables number which are going to use register increases than they may create overhead on register variable resource utilization.3) It may cause compilation overhead as if some body changes code inside inline function than all calling location will also be compiled.4) If used in header file, it will make your header file size large and may also make it unreadable.5) If somebody used too many inline function resultant in a larger code size than it may cause thrashing in memory. More and more number of page fault bringing down your program performance.6) Its not useful for embeded system where large binary size is not preferred at all due to memory size constraints.

Advantages & Disadvantages of reference parameterAdvantages of passing by reference:

1. It allows us to have the function change the value of the argument, which is sometimes useful.

20

Page 21: MODULE 1

2. Because a copy of the argument is not made, it is fast, even when used with large structs or classes.3. We can pass by const reference to avoid unintentional changes.4. We can return multiple values from a function. 

Disadvantages of passing by reference:

1. Because a non-const reference can not be made to a literal or an expression, reference arguments must be normal variables.2. It can be hard to tell whether a parameter passed by reference is meant to be input, output, or both.3. It’s impossible to tell from the function call that the argument may change. An argument passed by value and passed by reference looks the same. We can only tell whether an argument is passed by value or reference by looking at the function declaration. This can lead to situations where the programmer does not realize a function will change the value of the argument.4. Because references are typically implemented by C++ using pointers, and dereferencing a pointer is slower than accessing it directly, accessing values passed by reference is slower than accessing values passed by value.

Write a function that uses reference variables as arguments to swap the values of a pair of strings

#include<iostream>using namespace std;void swap(int &i, int &j){int temp = i;i = j;j = temp;}int main(){int i,j;cin>>i>>j;cout << i << j << endl;swap(i,j);cout << i << j;return 0;}

Difference between const and #define

21

Page 22: MODULE 1

Both are keywords used to create named constants in C++ however the #define statement is used as a preprocessor directive that serves to merely replace a named constant in your program with another text value such as:

#define PI 3.14159

which substitutes the text 3.14159 in every location where PI occurs in your source code and is retained in the language for some legacy compatability to be found with the C language subset of C++.

The const keyword denotes a named variable that is designated by a type (such as int) that is read-only (or constant) during the run-time of the program, and is utilized by the compiler rather than the preprocessor, whose value is subject to be changed during design time in the program.

const int myX = 4;

That allocates space in memory and assigns the value 4 to the integer. The 'const' thing means that the code you write cannot change the value of myX. If you try to, the compiler generates an error.

#define MYX 4

That merely substitutes 4 whenever MYX is used in the code.Function overloadingOverloading is the reuse of the same function name or symbol for two or more distinct functions or operations".Function overloading is the general concept of c++. A function can be declared more than once with different operations. This is called function overloading. In “C” language, the same function name is illegal to declare more than once. But c++ is benefited with this feature. It is the compiler job which one is the right to choose. If it makes sense to you then I should say that one function name for different operations have the advantage of good readability of a program. 

You overload a function name f by declaring more than one function with the name f in the same scope. The declarations of f must differ from each other by the types and/or the number of arguments in the argument list. When you call an overloaded function named f, the correct function is selected by comparing the argument list of the function call with the parameter list of each of the overloaded candidate functions with the name f. A candidate function is a function that can be called based on the context of the call of the overloaded function name.Consider a function print, which displays an int. As shown in the following example, you can overload the functionprint to display other types, for example, double and char*. You can have three functions with the same name, each performing a similar operation on a different data type:

#include <iostream>using namespace std;

void print(int i) {

22

Page 23: MODULE 1

cout << " Here is int " << i << endl;}void print(double f) { cout << " Here is float " << f << endl;}

void print(char* c) { cout << " Here is char* " << c << endl;}

int main() { print(10); print(10.10); print("ten");}

The following is the output of the above example: Here is int 10 Here is float 10.1 Here is char* ten

Function overloading based on vector parameter types is supported.C++ Scope Resolution Operator ::

The :: (scope resolution) operator is used to qualify hidden names so that you can still use them. You can use the unary scope operator if a namespace scope or global scope name is hidden by an explicit declaration of the same name in a block or class. For example:int count = 0; int main(void) { int count = 0; ::count = 1; // set global count to 1 count = 2; // set local count to 2 return 0;}

The declaration of count declared in the main() function hides the integer named count declared in global namespace scope. The statement ::count = 1 accesses the variablenamed count declared in global namespace scope.You can also use the class scope operator to qualify class names or class member names. If a class member name is hidden, you can use it by qualifying it with its class name and the class scope operator.In the following example, the declaration of the variable X hides the class type X, but you can still use the static class member count by qualifying it with the class type X and the scope resolution operator.

#include <iostream>using namespace std; class X{public: static int count;

23

Page 24: MODULE 1

};int X::count = 10; // define static data member int main (){ int X = 0; // hides class type X cout << X::count << endl; // use static member of class X}

How relationship between classes are foundThe three main types of relationships between classes are generalization (inheritance), aggregation, and association.

Generalization - This implies an "is a" relationship. One class is derived from another, the base class. Generalization is implemented as inheritance in C++. The derived class has more specialization. It may either override the methods of the base, or add new methods. Examples are a poodle class derived from a dog class, or a paperback class derived from a book class.

Aggregation - This implies a "has a" relationship. One class is constructed from other classes, that is, it contains objects of any component classes. For example, a car class would contain objects such as tires, doors, engine, and seats.

Association - Two or more classes interact in some manner. They may extract information from each other, or update each other in some way. As an example, a car class may need to interact with a road class, or if you live near any metropolitan area, the car class may need to pay a toll collector class.

Assume that you've been asked by the local zoo to write a program that will be used to study animals in order to create better habitats. What classes might be needed? An animal class is a good starting point.

class Animal {private:     int itsAge;     float itsWeight;public:     // Accessor methods have been left out as a simplification     void move() {cout << "Animal Moving\n";}     void speak() {cout << "Animal Speaking\n";}     void eat() {cout << "Animal Eating\n";}}

To better study a particular type of animal, it is necessary to generalize.

class Duck: public Animal {private: public:     // Accessor methods have been left out as a simplification     void move() {cout << "Waddle\n";}

24

Page 25: MODULE 1

     void speak() {cout << "Quack\n";}}

The Duck class has inherited some methods and members from Animal, and has made some of its methods more specialized. Not everyone can waddle and quack.An animal consists of certain parts: for instance, head, body, and skin. It is an aggregation of these parts. The animal class, likewise, can be an aggregation of many other classes.

class Animal {private:     int itsAge;     float itsWeight;     Head itsHead;     Body itsBod;     Heart itsHeart;public:     // Accessor methods have been left out as a simplification     void move() {cout << "Animal Moving\n";}     void speak() {cout << "Animal Speaking\n";}     void eat() {cout << "Animal Eating\n";}}

Association is a logical relationship. The classes need to know each others interfaces and need to interact but there is no formal "is a" or "has a" relationship as in generalization and aggregation, respectively. As an example, a zookeeper class would need associations with the animal classes. Interactions between these classes would be seen through out the zoo program.

Difference between Function overloading &overridingOverloading - Two or more functions having same name but different siganture(i.e arguements or return types) for eg. we have a function named as area then area();,float area();,area(float a,float b);,float area (float a,float b);

Overriding - When a function of base class is re-defined in the derived class.for eg.base class{area(float a,float b);}derive class{float area();} 1.In overloading,there is a relation ship between methods available in the same class where as in overridding,there is relationship between a super class method and subclass method.2. overloading doesn't block inheritence from the superclass where as overridding blocks inheritence.3. in overloading,seperate methods share the same name where as in overridding,subclass

25

Page 26: MODULE 1

methods replaces the superclass.

4.overloading must have different method signatures where as overriding must have same signature. Function overloading is done when you want to have the same function with different parametersvoid Print(string s);//Print stringvoid Print(int i);//Print integerFunction overriding is done to give a different meaning to the function in the base class

class Stream//A stream of bytes{public virtual void Read(){//read bytes}}

class FileStream:Stream//derived class{public override void Read(){//read bytes from a file}}class NetworkStream:Stream//derived class{public override void Read(){//read bytes from a network}}Read a sequence of words from input. Use QUIT as a word that terminates the input. Print the words in the order they were entered. Don’t print a word twice.#include<iostream>#include<conio.h>#include<string>

using namespace std;

int main(){ string word[100]; string arr[100]; int i=0,j,k,m,n;

while(1) { cout<<"enter word: \n"; cin>>word[i]; if(word[i]=="quit") break; i++; }

26

Page 27: MODULE 1

for(j=i,m=0;j>=0,m<=i;m++) { for(k=j-1;k>=0;k--) { if(word[j] == word[k]) goto start; }

arr[m]=word[j]; start: j--; }

for(n=m;n>0;n--) cout<<arr[n]<<"\n";

getch(); }

Using reference variable, define a function to interchange the values of two variables.#include <iostream>using namespace std;

// function declarationvoid swap(int &x, int &y);

int main (){ // local variable declaration: int a = 100; int b = 200; cout << "Before swap, value of a :" << a << endl; cout << "Before swap, value of b :" << b << endl;

/* calling a function to swap the values using variable reference.*/ swap(a, b);

cout << "After swap, value of a :" << a << endl; cout << "After swap, value of b :" << b << endl; return 0;}

27

Page 28: MODULE 1

When the above code is put together in a file, compiled and executed, it produces the following result:

Before swap, value of a :100Before swap, value of b :200After swap, value of a :200After swap, value of b :100

Pointers and ReferencesPointers and references are essentially variables that hold memory addresses as their values. You learned before about the various different data types such as: int,double, and char. Pointers and references hold the addresses in memory of where you find the data of the various data types that you have declared and assigned. The two mechanisms, pointers and references, have different syntax and different traditional uses.

Declaring pointers and references

When declaring a pointer to an object or data type, you basically follow the same rules of declaring variables and data types that you have been using, only now, to declare a pointer of SOMETYPE, you tack on an asterix * between the data type and its variable.

SOMETYPE* sometype; 

int* x; 

To declare a reference, you do the exact same thing you did to declare a pointer, only this time, rather than using an asterix *, use instead an ampersand &.

SOMETYPE& sometype; 

int& x; 

Spacing in C++ does not matter, so the following pointer declarations are identical:SOMETYPE*  sometype; SOMETYPE * sometype; SOMETYPE  *sometype; 

The following reference declarations are identical as well:

SOMETYPE&  sometype; SOMETYPE & sometype; SOMETYPE  &sometype; 

28

Page 29: MODULE 1

The "address of" operator

In C++, there is another operator , the "address of" operator, which is denoted by the ampersand & symbol. The "address of" operator does exactly what it says, it returns the "address of" a variable, a symbolic constant, or a element in an array, in the form of a pointer of the corresponding type. To use the "address of" operator, you tack it on in front of the variable that you wish to have the address of returned.

SOMETYPE* x = &sometype; // must be used as rvalue 

Now, do not confuse the "address of" operator with the declaration of a reference. Because use of operators is restricted to rvalues, or to the right hand side of the equation, the compiler knows that &SOMETYPE is the "address of" operator being used to denote the return of the address of SOMETYPE as a pointer.Furthermore, if you have a function which has a pointer as an argument, you may use the "address of" operator on a variable to which you have not already set a pointer to point. By doing this, you do not necessarily have to declare a pointer just so that it is used as an argument in a function, the "address of" operator returns a pointer and thus can be used in that case too.

SOMETYPE MyFunc(SOMETYPE *x) {   cout << *x << endl; } 

int main() {   SOMETYPE i; 

  MyFunc(&i); 

  return 0; } 

Assigning pointers and references

As you saw in the syntax of using the "address of" operator, a pointer is assigned to the return value of the "address of" operator. Because the return value of an "address of" operator is a pointer, everything works out and your code should compile. To assign a pointer, it must be given an address in memory as the rvalue, else, the compiler will give you an error.

int x; int* px = &x; 

29

Page 30: MODULE 1

The above piece of code shows a variable x of type int being declared, and then a pointer px being declared and assigned to the address in memory of x. The pointer px essentially "points" to x by storing its address in memory. Keep in mind that when declaring a pointer, the pointer needs to be of the same type pointer as the variable or constant from which you take the address.Now here is where you begin to see the differences between pointers and references. To assign a pointer to an address in memory, you had to have used the "address of" operator to return the address in memory of the variable as a pointer. A reference however, does not need to use the "address of" operator to be assigned to an address in memory. To assign an address in memory of a variable to a reference, you just need to use the variable as the rvalue.

int x; int& rx = x; 

The above piece of code shows a variable x of type int being declared, and then a reference rx being declared and assigned to "refer to" x. Notice how the address of x is stored in rx, or "referred to" by rx without the use of any operators, just the variable. You must also follow the same rule as pointers, wherein you must declare the same type reference as the variable or constant to which you refer.Hypothetically, if you wanted to see what output a pointer would be...

#include <iostream.h> 

int main() {   int someNumber = 12345;   int* ptrSomeNumber = &someNumber; 

  cout << "someNumber = " << someNumber << endl;   cout << "ptrSomeNumber = " << ptrSomeNumber << endl; 

  return 0; } 

If you compiled and ran the above code, you would have the variable someNumber output 12345 while ptrSomeNumber would output some hexadecimal number (addresses in memory are represented in hex). Now, if you wanted to cout the value pointed to by ptrSomeNumber, you would use this code:

#include <iostream.h> 

int main() {   int someNumber = 12345;   int* ptrSomeNumber = &someNumber; 

  cout << "someNumber = " << someNumber << endl;   cout << "ptrSomeNumber points to " << *ptrSomeNumber << endl; 

30

Page 31: MODULE 1

  return 0; } 

So basically, when you want to use, modify, or manipulate the value pointed to by pointer x, you denote the value/variable with *x.Here is a quick list of things you can do with pointers and references:

You can assign pointers to "point to" addresses in memory You can assign references to "refer to" variables or constants You can copy the values of pointers to other pointers You can modify the values stored in the memory pointed to or referred to by pointers

and/or references, respectively You can also increment or decrement the addresses stored in pointers You can pass pointers and/or references to functions (Further information on "Passing by

reference" can be found HERE)

The Null pointer

Remember how you can assign a character or string to be null? If you don't remember, check out HERE. The null character in a string denotes the end of a string, however, if a pointer were to be assigned to the null pointer, it points to nothing. The null pointer is often denoted by 0 or null. The null pointer is often used in conditions and/or in logical operations.

#include <iostream.h> 

int main() {   int x = 12345;   int* px = &x; 

  while (px) {     cout << "Pointer px points to something\n";     px = 0;   } 

  cout << "Pointer px points to null, nothing, nada!\n"; 

  return 0; } 

If pointer px is NOT null, then it is pointing to something, however, if the pointer is null, then it is pointing to nothing. The null pointer becomes very useful when you must test the state of a pointer, whether it has a value or not.

31

Page 32: MODULE 1

Dynamic Memory Allocation

We have learned about assigning pointers using the "address of" operator because it returned the address in memory of the variable or constant in the form of a pointer. Now, the "address of" operator is NOT the only operator that you can use to assign a pointer. In C++ you have yet another operator that returns a pointer, which is the new operator. The new operator allows the programmer to allocate memory for a specific data type, struct, class, etc, and gives the programmer the address of that allocated sect of memory in the form of a pointer. The new operator is used as an rvalue, similar to the "address of" operator. Take a look at the code below to see how the new operator works.

int n = 10; SOMETYPE *parray, *pS; int *pint; 

parray = new SOMETYPE[n]; pS = new SOMETYPE; pint = new int; 

By assigning the pointers to an allocated sect of memory, rather than having to use a variable declaration, you basically override the "middleman" (the variable declaration. Now, you can allocate memory dynamically without having to know the number of variables you should declare. If you looked at the above piece of code, you can use the new operator to allocate memory for arrays too, which comes quite in handy when we need to manipulate the sizes of large arrays and or classes efficiently. The memory that your pointer points to because of the new operator can also be "deallocated," not destroyed but rather, freed up from your pointer. The delete operator is used in front of a pointer and frees up the address in memory to which the pointer is pointing.

delete parray; delete pint; 

The memory pointed to by parray and pint have been freed up, which is a very good thing because when you're manipulating multiple large arrays, you try to avoid losing the memory someplace by leaking it. Any allocation of memory needs to be properly deallocated or a leak will occur and your program won't run efficiently. Essentially, every time you use the new operator on something, you should use the delete operator to free that memory before exiting. The deleteoperator, however, not only can be used to delete a pointer allocated with the new operator, but can also be used to "delete" a null pointer, which prevents attempts to delete non-allocated memory (this actions compiles and does nothing).The new and delete operators do not have to be used in conjunction with each other within the same function or block of code. It is proper and often advised to write functions that allocate memory and other functions that deallocate memory.

32

Page 33: MODULE 1

Returning pointers and/or references from functions

When declaring a function, you must declare it in terms of the type that it will return, for example:

int MyFunc(); // returns an int SOMETYPE MyFunc(); // returns a SOMETYPE 

int* MyFunc(); // returns a pointer to an int SOMETYPE *MyFunc(); // returns a pointer to a SOMETYPE SOMETYPE &MyFunc(); // returns a reference to a SOMETYPE 

The above piece of code shows how to basically declare a function that will return a reference or a pointer.

SOMETYPE *MyFunc(int *p) {    ...    ...    return p; } 

SOMETYPE &MyFunc(int &r) {   ...   ...   return r; } 

Within the body of the function, the return statement should NOT return a pointer or a reference that has the address in memory of a local variable that was declared within the function, else, as soon as the function exits, all local variables ar destroyed and your pointer or reference will be pointing to some place in memory that you really do not care about. Having a dangling pointer like that is quite inefficient and dangerous outside of your function.However, within the body of your function, if your pointer or reference has the address in memory of a data type, struct, or class that you dynamically allocated the memory for, using the new operator, then returning said pointer or reference would be reasonable.

SOMETYPE *MyFunc()  //returning a pointer that has a dynamically {           //allocated memory address is proper code    int *p = new int[5];    ...    ...    return p; } 

33

Page 34: MODULE 1

SIMILARITIES & DIFFERENCES

NULL REFERENCE

A reference and a const pointer are almost the same since they point only to one object. A difference of course is a reference cannot refer to a NULL object, while a const pointer can refer to a NULL object.

INITIALIZATIONBoth a reference and a const pointer need to be initialized during definition.

CAVEATSOne needs  to understand that though references look cleaner and safer, there are surely means of exploiting them by making the reference in invalid reference.

char *p = 0; //NULLint &i  = *p; //invalid reference

Another thing if obviously returning a reference to a variable local to the stack of a function.

CONSTANT REFERENCE / POINTER

Since a reference only points to / refers to one object, it's constant by nature. There is technically no const reference. Binding an object to a reference happens at the time of definition.

There is a const pointer though and the binding behaviour changes based on what the pointer is declared as.1. A pointer can be re-assigned any number of times while a reference can not be reassigned

after initialization.2. A pointer can point to NULL while reference can never point to NULL3. You can't take the address of a reference like you can with pointers4. There's no "reference arithmetics" (but you can take the address of an object pointed by a

reference and do pointer arithmetics on it as in &obj + 5).

34

Page 35: MODULE 1

35