P. 1
ADS_UNIT_I

ADS_UNIT_I

|Views: 17|Likes:
Published by api-26548538
PDF copy of ADS Unit I notes.
PDF copy of ADS Unit I notes.

More info:

Published by: api-26548538 on Oct 18, 2008
Copyright:Attribution Non-commercial

Availability:

Read on Scribd mobile: iPhone, iPad and Android.
download as PDF, TXT or read online from Scribd
See more
See less

05/09/2014

pdf

text

original

C++ OVERVIEW Object Oriented Programs are organized around the data, with the key principle being “ data

controlling access to code”. OOP Principles : 1. Encapsulation : The mechanism that binds together code and other data it manipulates. 2. Polymorphism : “One interface, multiple methods “. It is the attribute that allows one interface to control access to a general class of actions. 3. Inheritance : The process by which one object can acquire the properties of another object. Some C++ Fundamentals #include <iostream.h> int main() { int i; cout << "This is output.\n"; // this is a single line comment

/* you can still use C style comments */ // input a number using >> cout << "Enter a number: "; cin >> i; // now, output a number using << cout << i << " squared is " << i*i << "\n"; return 0; }

1

Note : 1. When inputting a string using >> operator , it terminates at blank space. 2. In C++ local variables can be declared anywhere in the block. 3. C++ supports Boolean data type. Keyword – bool. Automatic conversions allow “Boolean” values to be converted to “integers” and vice-versa. General form of C++ program #includes base-class declarations derived-class declarations non member function prototypes int main() { } non member function definitions. Overview 1. Classes and Objects 2. Constructors and Destructors 3. Function Overloading 4. Operator Overloading 5. Inheritance 6. Templates

2

CLASSES AND OBJECTS CLASS is the basic unit of encapsulation ( LOGICAL ABSTRACTION ). OBJECT is an instance of a class ( PHYSICAL ABSTRACTION ). Access Specifiers : 1. Public : Members accessible to other parts of the program. Members accessible to other members of

2. Private ( Default ) : the class. 3. Protected : •

Needed in Inheritance

Variables that are elements of a class are called “Member Variables” or “Data Members”. Functions declared within a class are called “Member Function”. :

Constructors •

A Special function that is a member of a class and has the same name as that class. It is called when the object is created (automatically). Used for initializations – arguments passed to constructor help initialize an object. #include <iostream.h> class myclass { int a, b; public: myclass(int i, int j) {a=i; b=j;} void show() {cout << a << " " << b;} }; int main() { myclass ob(3, 5); ob.show(); return 0; } 3

• • Ex1:

Note : Constructor with One parameter is a Special case – Initialize the object as Class Object(argument); OR Class Object = argument;

Ex2: #include <iostream.h> class X { int a; public: X(int j) { a = j; } int geta() { return a; } }; int main() { X ob = 99; // passes 99 to j cout << ob.geta(); // outputs 99 return 0; } Destructors : • • Complement of a constructor. Used for performing some actions when an object is destroyed.

NOTE : CONSTRUCTORS AND DESTRUCTORS DO NOT HAVE A RETURN VALUE

4

INLINE FUNCTIONS • • Keyword – inline Shortcut functions that are not actually called ; rather, code is expanded inline at the point of invocation. Used to write efficient code : use only for very small functions. When a function is defined inside a class declaration, it is automatically made into “inline” function if possible. Constructor and Destructor functions may also be inlined, either by default or explicitly.

NOTE : INLINE is just a request , not a command to the compiler. Ex1: #include<iostream.h> inline int max(int a, int b) { return a>b ? a : b; } int main() { cout << max(10, 20); cout << " " << max(99, 88); return 0; } Compiler sees it as : int main() { cout << (10>20 ? 10 : 20); cout << " " << (99>88 ? 99 : 88); return 0; }

5

EX2: #include <iostream.h> class myclass { int a, b; public: void init(int i, int j); void show(); }; // Create an inline function. inline void myclass::init(int i, int j) { a = i; b = j; } // Create another inline function. inline void myclass::show() { cout << a << " " << b << "\n"; } int main() { myclass x; x.init(10, 20); x.show(); return 0; }

6

FRIEND FUNCTIONS • A friend function has access to all private & protected members of the class for which it is a “friend”. Declaration : include its prototype within the class preceded by keyword “friend”. #include <iostream.h> class myclass { int a, b; public: friend int sum(myclass x); void set_ab(int i, int j); }; void myclass::set_ab(int i, int j) { a = i; b = j; } // Note: sum() is not a member function of any class. int sum(myclass x) { /* Because sum() is a friend of myclass, it can directly access a and b. */ return x.a + x.b; } int main() { myclass n; n.set_ab(3, 4); cout << sum(n); return 0; }

• Ex1:

7

Uses : • When overloading certain type of operators. • • Ex2: #include <iostream.h> const int IDLE = 0; const int INUSE = 1; class C2; // forward declaration Makes the creation of some type of I/O functions easier. 2 or more classes may contain members that are interrelated relative to other parts of the program.

class C1 { int status; public:

// IDLE if off, INUSE if on screen

void set_status(int state); friend int idle(C1 a, C2 b); }; class C2 { int status; // IDLE if off, INUSE if on screen public: void set_status(int state); friend int idle(C1 a, C2 b); }; void C1::set_status(int state) { status = state; } void C2::set_status(int state) { status = state; }

8

int idle(C1 a, C2 b) { if(a.status || b.status) return 0; else return 1; } int main() { C1 x; C2 y; x.set_status(IDLE); y.set_status(IDLE); if(idle(x, y)) cout << "Screen can be used.\n"; else cout << "In use.\n"; x.set_status(INUSE); if(idle(x, y)) cout << "Screen can be used.\n"; else cout << "In use.\n"; return 0; } NOTE : FORWARD DECLARATION OR REFERENCE OF A CLASS . class c1;

9

A FRIEND OF ONE CLASS MAY BE A MEMBER OF ANOTHER CLASS. Ex3 : #include <iostream.h> const int IDLE = 0; const int INUSE = 1; class C2; // forward declaration

class C1 { int status; public:

// IDLE if off, INUSE if on screen

void set_status(int state); int idle(C2 b); }; class C2 { int status; public: void set_status(int state); friend int C1::idle(C2 b); }; void C1::set_status(int state) { status = state; } void C2::set_status(int state) { status = state; } // now a member of C1

// IDLE if off, INUSE if on screen

10

// idle() is member of C1, but friend of C2 int C1::idle(C2 b) { if(status || b.status) return 0; else return 1; } int main() { C1 x; C2 y; x.set_status(IDLE); y.set_status(IDLE); if(x.idle(y)) cout << "Screen can be used.\n"; else cout << "In use.\n"; x.set_status(INUSE); if(x.idle(y)) cout << "Screen can be used.\n"; else cout << "In use.\n"; return 0; } Restrictions : 1. A derived class does not inherit friend functions. 2. They may not have a storage-class specifier. ( They may not be declared as static or extern ).

11

FRIEND CLASSES • The friend class and all of its member functions have access to the private member defined within the other class. Friend classes only has access to names defined within the other class. It does not inherit the other class. They are seldom used. #include <iostream.h> class TwoValues { int a; int b; public: TwoValues(int i, int j) { a = i; b = j; } friend class Min; }; class Min { public: }; int Min::min(TwoValues x) { return x.a < x.b ? x.a : x.b; } int main() { TwoValues ob(10, 20); Min m; cout << m.min(ob); return 0; } int min(TwoValues x);

Ex :

12

STATIC CLASS MEMBERS
STATIC DATA MEMBERS • When a variable is declared static in a class, no matter how many objects of the class are created, only one copy of a static data member exists. All objects of that class share the same static variable. All static variables are initialized to 0 before the first object is created. #include <iostream.h> class shared { static int a; int b; public: void set(int i, int j) {a=i; b=j;} void show(); } ; void shared::show() { cout << "This is static a: " << a; cout << "\nThis is non-static b: " << b; cout << "\n"; } int main() { shared x, y; x.set(1, 1); // set a to 1 x.show(); y.set(2, 2); // change a to 2 y.show(); x.show(); /* Here, a has been changed for both x and y because a is shared by both objects. */ return 0; }

• • Ex1:

13

• Ex2:

A static member variable exists before any objects of the class is created. Thus, it may be directly accessed in main(). #include <iostream.h> class shared { public: static int a; } ; int main() { // initialize a before creating any objects shared::a = 99; cout << "This is initial value of a: " << shared::a; cout << "\n"; shared x; cout << "This is x.a: " << x.a; return 0; }

Uses : • To provide access control to some shared resource used by all objects of a class. To keep track of the number of objects of a particular class type that are in existence. It virtually eliminates any need for global variables.

14

To control access of a scarce resource: Ex3: #include <iostream.h> class cl { static int resource; public: int get_resource(); void free_resource() {resource = 0;} }; int cl::get_resource() { if(resource) return 0; // resource already in use else { resource = 1; return 1; // resource allocated to this object } } int main() { cl ob1, ob2; if(ob1.get_resource()) cout << "ob1 has resource\n"; if(!ob2.get_resource()) cout << "ob2 denied resource\n"; ob1.free_resource(); // let someone else use it

if(ob2.get_resource()) cout << "ob2 can now use resource\n"; return 0; }

15

To keep track of the number of objects of a class Ex4: #include <iostream.h> class Counter { public: static int count; Counter() { count++; } ~Counter() { count--; } }; void f(); int main(void) { Counter o1; cout << "Objects in existence: "; cout << Counter::count << "\n"; Counter o2; cout << "Objects in existence: "; cout << Counter::count << "\n"; f(); cout << "Objects in existence: "; cout << Counter::count << "\n"; return 0; } void f() { Counter temp; cout << "Objects in existence: "; cout << Counter::count << "\n"; // temp is destroyed when f() returns }

16

STATIC MEMBER FUNCTIONS • A static member function may be called either by itself, independent of any object, by using the class name and the scope resolution operator, or in connection with an object. They have limited applications. One use is to “preinitialize” private static data before any object is actually created. #include <iostream.h> class static_type { static int i; public: static void init(int x) {i = x;} void show() {cout << i;} }; int main() { // init static data before object creation static_type::init(100); static_type x; x.show(); // displays 100 return 0; } Restrictions • They may only directly refer to other static members of the class. • • It does not have a “this” pointer. There cannot be a static and non-static version of the same function. It may not be virtual. They cannot be declared const or volatile.

• •

Ex :

• •

17

When Constructors and destructors are used • • A local object’s constructor is executed when the object’s declaration statement is encountered. The destructor is executed in the reverse order of constructor.

• • Ex:

Global object’s constructors execute before main() begins execution, in the order of their declaration. Global destructors execute in the reverse order after main() terminates. #include <iostream.h> class myclass { public: int who; myclass(int id); ~myclass(); } glob_ob1(1), glob_ob2(2); myclass::myclass(int id) { cout << "Initializing " << id << "\n"; who = id; } myclass::~myclass() { cout << "Destructing " << who << "\n"; } int main() { myclass local_ob1(3); cout << "This will not be first line displayed.\n"; myclass local_ob2(4); return 0; }

18

Scope Resolution Operator Uses : 1. Links a class name with a member name in order to tell the compiler what class the member belongs to. 2. It can allow access to a name in an enclosing scope that is “hidden” by a local declaration of the same name. Ex : A) int i; // global i void f() { int i; // local i i = 10; // uses local i . . . } B) int i; // global i

void f() { int i; // local i ::i = 10; // now refers to global i . . . } Nested Classes • • • Defining one class within another creates a nested class. A nested class is valid only within the scope of the enclosing class. They are seldom used.

19

Local Classes • • • Ex : #include <iostream.h> void f(); int main() { f(); //myclass not known here return 0; } void f() { class myclass { int i; public: void put_i(int n) { i=n; } int get_i() { return i; } } ob; ob.put_i(10); cout << ob.get_i(); } A class that is defined within a function. It is only known to that function. Not commonly used.

20

Passing Objects to functions • Through call by value mechanism ( A copy of the object passed is made). o When a copy of an object is generated because it is passed to a function, the object’s constructor is not called. o However, when a copy of the object inside a function is destroyed , its destructor is called. Ex : #include <iostream.h> class myclass { int i; public: myclass(int n); ~myclass(); void set_i(int n) { i=n; } int get_i() { return i; } }; myclass::myclass(int n) { i = n; cout << "Constructing " << i << "\n"; } myclass::~myclass() { cout << "Destroying " << i << "\n"; } void f(myclass ob); int main() { myclass o(1); f(o); cout << "This is i in main: "; cout << o.get_i() << "\n"; return 0; } void f(myclass ob) { ob.set_i(2); cout << "This is local i: " << ob.get_i(); cout << "\n"; }

21

Returning Objects • When an object is returned by a function , a temporary object is automatically created that holds the return value. After the value has been returned, the object is destroyed. #include <iostream.h> class myclass { int i; public: void set_i(int n) { i=n; } int get_i() { return i; } }; myclass f(); int main() { myclass o; o = f(); cout << o.get_i() << "\n"; return 0; } myclass f() { myclass x; x.set_i(1); return x; } // return object of type myclass

• Ex :

22

Object Assignment Assuming that both objects are of the same type, one object can be assigned to another. Ex : #include <iostream.h> class myclass { int i; public: void set_i(int n) { i=n; } int get_i() { return i; } }; int main() { myclass ob1, ob2; ob1.set_i(99); ob2 = ob1; // assign data from ob1 to ob2 cout << "This is ob2's i: " << ob2.get_i(); return 0; }

NOTE : By default all the data from one object is assigned to the other by use of a bit-by-bit copy.

23

The ‘this‘ Pointer • When a member function is called, it is automatically passed an implicit argument that is a pointer to the invoking object. This pointer is called this. this pointer is very important – o when operators are overloaded o Whenever a member function must utilize a pointer to the object that invoked it. #include <iostream.h> class pwr { double b; int e; double val; public: pwr(double base, int exp); double get_pwr() { return this->val; } }; pwr::pwr(double base, int exp) { this->b = base; this->e = exp; this->val = 1; if(exp==0) return; for( ; exp>0; exp--) this->val = this->val * this->b; } int main() { pwr x(4.0, 2), y(2.5, 1), z(5.7, 0); cout << x.get_pwr() << " "; cout << y.get_pwr() << " "; cout << z.get_pwr() << "\n"; return 0; } NOTE : • Friend functions are not members of a class and therefore are not passed a this pointer. • Static member functions do not have a this pointer. 24

Ex :

Dynamic Memory Allocation and Deallocation
C++ has 2 dynamic allocation operators: 1. new • • • : The new operator allocates memory. It returns a pointer to the start of allocated memory. new returns NULL ( older version of C++ ), or bad_alloc exception (std C++). • new automatically returns a pointer of the specified type.

2. delete : • The delete operator frees memory previously allocated using new. Note: Both new and delete can be overloaded.

Initializing Allocated Memory P_var = new var_type ( initializer ); To free Ex1: delete P_var; #include <iostream.h> int main() { int *p; p = new int; // *p = 100; or use p = new int(80); to initialise

cout << "At " << p << " "; cout << "is the value " << *p << "\n"; delete p; return 0; } Allocating arrays P_var = new array_type [size]; To free delete[] P_var;

Note: Dynamically allocated arrays cannot be initialized.

25

Ex2:

#include <iostream.h> int main() { int *p, i; p = new int [10]; // allocate 10 integer array for(i=0; i<10; i++ ) p[i] = i; for(i=0; i<10; i++) cout << p[i] << " "; delete [] p; // release the array return 0; }

Allocating Objects • When an object is created dynamically, a pointer is returned to it. It acts just like any other object. • Since it is a pointer to an object, the arrow operator is used to access members of the object. They may have constructors & destructors. Also, the constructors can be parameterized. One can allocate arrays of objects dynamically. Since no array allocated by new can have an initializer, one must make sure that if the class contains constructors, one should be parameterless.

Placement Forms of new and delete: • There is a specialized form of new, called the placement form. • It is primarily useful when overloading the new operator for special circumstances. • General form: P_var = new (location) type; Location specifies an address that is simply returned by new. • There is also a placement form of delete, which is used to free memory allocated by the placement form of new.

26

You're Reading a Free Preview

Download
scribd
/*********** DO NOT ALTER ANYTHING BELOW THIS LINE ! ************/ var s_code=s.t();if(s_code)document.write(s_code)//-->