Objected Oriented Programming Using C++ Unit 2
Objected Oriented Programming Using C++ Unit 2
Classes
A class is a way to bind the data and its associated functions together. It allows the data (and functions) to be hidden, if necessary from external use. When defining a class, we are creating a new abstract data type that can be treated like any other built-in data type. Generally, a class specification has two parts: 1. Class declaration 2 . Class function definitions The class declaration describes the type and scope of its members. The class function definitions describe how the class functions are implemented.
2
Classes
class identifier {access specifier: // Body of class having data members statements; //and functions members enclosed by curly braces {}. }; //The class declaration ends with the semicolon. The class body comprises data members and function members. The data members comprise abstract data that applies to all the object of class and is relevant to the aim of the program. The common characteristics of objects of class are described by the function members of the class.
3
Program
This is followed by body of function in braces{}. #include <iostream> class Market { // start of class declaration public: void Display(); // function prototype }; // end of class void Market::Display () //function definition outside the class {cout<< Welcome To This Market << endl; cout << Here is the price List <<endl; } void main() //main program {Market L1; // L1 is declared an object of class market L1.Display(); // L1 calls function display }
6
void showxy(); }; // end of class void point :: showxy() { cout << X coordinate << x << endl; cout << Y coordinate << y << endl; } void main() { point p; point q; p.getxy(10,12); p.showxy(); q.getxy(15,25); q.showxy(); } //end of main
int i; // global i void f() { int i; // local i ::i = 10; // now refers to global i .. .}
10
void main() { part p1, p2; p1.setpart(1996, 23, 1250.50); p2.setpart(2000, 243, 2350.50); cout<< first part details :<<endl; p1.showpart(); cout<< second part details :<<endl; p2.showpart(); }
12
DECLARATION OF CLASS
The form of code used for declaring a class is illustrated below. class X // class is keyword, X is the name of class { private: //access label private memberA; // memberA is a private member of class X. protected: // access label protected memberB; // MemberB is protected member ...... // dotted line stands for other data or functions public: //access label public ...... memberC; //memberC is a public member private: //a access label may be repeated memberD; // memberD is also a private member of class X };
13
PROTECTED: The class members declared protected are accessible by the function members of same class and friend functions and friend classes as well as by functions of derived classes. For all other operations protected members are similar to private members. PUBLIC: The class members declared public are accessible from inside or outside the class. Some of the public functions of class provide interface for accessing the private and protected members of the class. For instance, initialization of a class object with private or protected data is always carried through public functions. Some public function also provide interface for other classes.
15
Program
#include <iostream.h> class Market { private : int x,y,z; public: void Display1() ,cout<< Welcome! Here is the price List << endl;void Setprice (int a, int b, int c) // function defined in class {x = a, y = b, z = c;} void Display2 () ,cout<< Price of item1 = << x<<endl; cout<< Price of item2 = << y<<endl; cout<< Price of item3 = << z<<endl; } }; void main() { Market L1; L1.Setprice (4,6,2); // Object L1 is initialized by function // setprice() L1. Display1(); // Functions called by using dot operator. L1.Display2(); }
18
void List ::Setprice (int a[4] ) // Definition of Setprice () { for ( int j = 0; j< 4; j++) x[j] = a [j] ; } void main() { List L1; // L1 is an object of class List int P[4] = {6,5,4,8} ; L1.Setprice(P) ; // P is const pointer to the array L1. Display1(); L1.Display2(); }
21
void List :: Setmarks (int a[4] ) //Definition of setmarks () {for ( int j = 0; j< 4; j++) // outside the class x[j] = a [j] ;} void List:: Setnames(char b[4][20] ) //Definition of Setnames {for ( int m = 0 ; m<4; m++) // outside the class {for (int p = 0 ; p<20; p++) Names[m][p] = b[m][p] ;} } void main() { List L1; char Students [4] [20] ; cout<<Enter the names of 4 students: ; for( int i =0; i< 4;i++) cin.getline ( Students[i],20); // Reading names from keyboard cout<<Enter Marks.<< endl; int P [4]; for (int k =0; k<4;k++) cin>> P[k]; {L1.Setmarks(P) ; // Putting in an array parameter L1.Setnames (Students);} // Putting in string parameter L1.Display1(); L1.Display2(); }
23
int set :: largest(void) { if(m >= n) return(m); else return(n); } void set :: input(void) { coat "Input values of m and n" \n"; cin m n; } void set :: display(void) { cout Largest value largest() \n"; } int main() { set A; A.input(); A.display(); return 0; }
25
destructor
The destructor function removes the object from the computer memory after its relevance is over. For a local object the destructor is called at the end of the block enclosed by the pair of braces { } wherein the object is created and for a static object it is called at the end of main() function. It releases the memory occupied by the object and returns it to heap. The destructor function also has same name as class but it is preceded by the tilde symbol (~) and has no parameters. It is a good programming practice to provide a destructor explicitly. If it is not provided explicitly in the program it is provided by the system.
27
#include <iostream.h> class Cubicle { private: int x, y, z; public: Cubicle ( int , int, int ); //constructor prototype int volume() {return ( x*y*z);} }; // End of class Cubicle::Cubicle(int a, int b, int c ) // Constructor {x = a, y = b, z = c ; // defined outside class cout<<constructed called<<endl;int main() { Cubicle cube1(3,3,3) ; // object 1 with arguments 3,3,3 Cubicle cube2(4,5,6); //object 2 Cubicle cube3 (2,4,5); //object 3 cout << Volume of cube1 = <<cube1.volume()<<\n; cout << Volume of cube2 = <<cube2.volume()<<\n; cout << Volume of cube3 = <<cube3.volume()<<\n; return 0 ; }
28
Program
TYPES OF CONSTRUCTORS
At least one parameter should be different or at least of different type. The different types of constructors are listed below. (i) Default Constructor (ii) Parameterized Constructor (iii) Copy constructor Default constructor A constructor that accepts no parameters is called the default constructor. The default constructor for class A is A::A(). If no such constructor is defined, then the compiler supplies a default constructor.
29
Parameterized Constructors
The constructors that can take arguments are called parameterized constructors. #include <iostream.h> class integer{ int m, n; public: integer(int, int); // constructor declared void display(void) { cout<<m = <<m<<\n; cout<<n = <<n<<\n; } }; integer :: integer(int x, int y) // constructor defined { m = x; n = y; }
30
int main() { integer int1(0,100); // constructor called Implicitly integer int2 = integer(25, 75); //constructor called explicitly cout "\nOBJECT1 "\n;int1.display(); cout "\n08JECT2 \n; int2.display(); return 0; }
31
Copy constructor
A constructor can accept a reference to its own class as a parameter. Program of all types of constructors #include <iostream.h> class Cubicle { private: int x, y, z; public: Cubicle () { x = 3, y = 4, z = 2 ; // default constructor cout << Default constructor called.;~ Cubicle () { cout<< Destructor called to remove object.\n; }
32
Cubicle (int a, int b, int c ){x = a, y = b , z= c; cout << Parametric constructor called. ;Cubicle (Cubicle & cubeA) // copy constructor definition { x = cubeA.x , y = cubeA.y , z = cubeA.z ; cout << \nCopy constructor called. ;int volume() {return ( x*y*z);} // definition of function volume }; // End of class int main() {{ Cubicle cube1; //scope of cube1 is this program block{} cout << \nVolume of cube1 = <<cube1.volume() <<\n ;Cubicle cube2(6,5,4) ; // Scope main() cout << \nVolume of cube2 = <<cube2.volume(); { Cubicle cube3 (cube2) ; //Scope of cube3 is this block {} cout << \nVolume of cube3 = << cube3.volume( )<<\n;return 0 ; }
33
void Display1() // Displays private data of object. ,cout <<x = <<this->x <<, y = <<this->y << , z = <<(*this).z <<endl;void Display2() {cout << this<<endl; } // gives value of this private: int x ,y, z; // private data }; // end of class int Cuboid::surface_area() // definition of surface area {return 2*(x*y +y*z +z*x);} int Cuboid::volume() // definition of volume {return x*y*z ;} int main() { Cuboid C1(5,6,4), C2(7,8,5) ; // C1 and C2 are two objects C1.Display1(); C1.Display2(); // value of this pointer for C1 cout <<&C1<<endl; // Address of C1 C2. Display1(); C2. Display2(); // value of this for C2 cout << &C2<<endl; // Address of object C2 cout << Volume of cuboid C1 = <<C1.volume()<<\n; cout<< Volume of cuboid C2 = << C2.volume()<<\n; cout<<Surface area of C1 = << C1.surface_area()<<\n; cout<<Surface area of C2 = << C2.surface_area()<<\n; return 0 ; }
35
The following points should be noted about friend functions to classes. 1. If a function F is friend to class B, then F can access all the members of class B. 2. The friendship is granted by the class and not extracted by the function. Therefore, the friend function has to be so declared in the body of the class as illustrated above. 3. Function prototype of friend function preceded by keyword friend is declared inside the class body but the function is defined outside the class body. 4. Friend function is not a member function of the class to which it is friend. Therefore, the scope resolution operator is not required while defining the friend function outside the class body. 5. A class may have any number of friend functions. And a function may be friend to any number of classes. 6. A friend function may be declared any where in the class. The access specifiers, i.e. public, protected or private do not affect a friend function.
37
Program
#include <iostream.h> class Rect { friend int Area(const Rect &a); // friend function Area int x,y; // private by default public: Rect (int L, int W){ x = L,y = W;} // constructor function }; // end of class int Area (const Rect &b) // definition of friend function {return b.x*b.y;}; // scope resolution operator not needed int main() { Rect R1(5,6), R2(3,4) ; //declaration of two objects R1 and R2 cout << Area of R1= << Area ( R1 ) <<\n; cout << Area of R2 = << Area ( R2 )<<\n; return 0 ; }
38
39
class Sqr { // class Sqr int side; // private by default public: Sqr (int C){ side = C;} int Area ( ) {return side*side;} friend void Display (Rect R , Sqr S ); // friend function to Sqr }; //end of class void Display ( Rect R, Sqr S) // Definition of friend function ,cout <<Area of rect = << R.area()<<endl; cout <<Area of Square = << S.Area()<< endl;int main() {Rect R1(10,5); Sqr S1 (10); Display ( R1, S1 ); return 0 ; }
40
FRIEND CLASSES
When all or most of the functions of a class need access to data members and function members of another class, the whole class may be declared friend to the class. For instance, if the functions of a class say class A need to access the public, private and protected members of another class say class B, the class A may be Class B { friend class A; //declaration that class A is friend of B Private: statements friend class C; //declaration that class C is friend of B public: Other_statements; };
41
42
Program
#include <iostream.h> class Cuboid { friend class paint; // Declaration of friend class public: void sides(int , int, int); int Area(); int volume(); int x , y, z; }; //end of class Cuboid void Cuboid:: sides (int L, int W, int H ) {x = L, y = W,z = H; } // Setting the sides of Cuboid int Cuboid::Area() //Definition of area {return 2*(x*y +y*z +z*x);}
43
int Cuboid::volume() // definition of volume {return x*y*z ;} class paint{ //declaration of friend class paint private: int R; public: paint () { R = 1;} // default constructor paint ( int S) { R = S;} // parametric constructor Cuboid C; // C is the object of class Cuboid int area (){return C.Area ();} int cost(int R , Cuboid C ) // R is the rate and C is object {return R* C.Area () ;} // of Cuboid. cost() is a function }; int main() {Cuboid C1 ; // C1 is object of class Cuboid C1.sides (5,6,5 ); paint P1 ; // P1 is object of class paint int k = 4; cout << Volume of C1 = <<C1.volume()<<\n; cout<<Surface area of C1 = <<C1.Area()<<\n; cout<<Cost of painting P1 = << P1.cost(k, C1)<<\n; return 0 ; }
44
POINTER TO A CLASS
Pointer to a class may be declared in the same way as it is done for integer or double numbers. Let us have a class by name List and let L1 be an object of this class. Let ptr be the pointer to the class. For declaration of pointer to List we may write the code as below. List L1 ; // declaration that L1 is an object of class List List *ptr; // declaration of pointer to List ptr = &(List) L1; // assignment of value to ptr The last line may as well be written as ptr = &List (L1);
45
#include <iostream.h> class List { private : int x,y; //let x = the no of items, y = price of one item. public: void Setdata (int a, int b ) //A public function to access x,y. {cout << Enter number of items : ; cin >>a ; cout <<Enter price of one item : ; cin >> b ; x = a, y = b; } void Display1 ( ) {cout<<Number of items = <<x <<endl; } void Display2 () {cout<<Price of each item = <<y <<endl ; } void Display3 () {cout<<Cost of <<x<< items at the rate of <<y<<per item = <<x*y<<endl;} }; // End of class void main() { List L1 ; List *ptr; // pointer to List ptr = &(List) L1; // assigning address of class object int i,j; (*ptr).Setdata (i,j); //values to be assigned by user ptr -> Display1 (); // (*ptr) and ptr-> are equivalent. ptr -> Display2(); (*ptr).Display3(); }
46
#include <iostream.h> class Rect { int x ,y; // private by default public: void Setsides ( int L,int W ){ x = L ,y = W ;} int Area( ) // Definition of function Area {return x*y;} }; // end of class int main() { Rect R1,R2,R3; void (Rect:: *ptrSet)(int,int) = & Rect :: Setsides; (R1.*ptrSet) (20,15); cout << Area of R1 = << R1.Area()<<endl; (R2.*ptrSet) (20,30); //object R2 calls function by its pointer cout << Area of R2 = << R2.Area()<<endl; Rect *ptr3 = &R3; // declaring pointer to object R3 of class (ptr3 ->*ptrSet)(16,10); //calling function by pointer to object cout << Area of R3 = << R3.Area()<<endl; return 0 ; }
47
49
#include <iostream.h> class Cuboid { public: static int x; // x declared static Cuboid( int W ): y(W) {} // constructor static void Display ( ) // static function ,cout << Height of all objects is = << z <<endl;int surface_area( ); int volume( ); private: int y; static int z ; // static variable }; // end of class int Cuboid :: x = 10; int Cuboid :: z = 5; int Cuboid::surface_area() {return 2*(x*y +y*z +z*x);}
50
int Cuboid::volume() {return x*y*z ;} int main() { Cuboid C1(6), C2(3) ; cout << C1.x = << C1.x << , C2.x = <<C2.x <<endl; Cuboid :: Display( ); // function call without an object cout << Volume of cuboid C1 << C1.volume()<<\n; cout<< Volume of cuboid C2 = << C2.volume()<<\n; cout<<surface area of C1 = << C1.surface_area()<<\n; cout<<surface area of C2 = << C2.surface_area()<<\n; return 0 ; }
51
int Cuboid :: x = 5; // static data member int Cuboid :: y =8 ; // static data member int Cuboid::surface_area() // definition of surface_area () {return 2*(x*y +y*z +z*x);} int Cuboid::volume() // definition of function volume() {return x*y*z ;} int main() { Cuboid C1(5), C2(8) ; cout<<Base area of all objects = << Cuboid::Base_area()<<endl; cout << Volume of cuboid C1 << C1.volume()<<\n; cout<< Volume of cuboid C2 = << C2.volume()<<\n; cout<<Surface area of C1 = << C1.surface_area()<<\n; cout<<Surface area of C2 = << C2.surface_area()<<\n; return 0 ; }
53
Local Classes
Classes can be defined and used inside a function or a block. Such classes are called local classes. Examples:
void test(int a) // function { ......... ......... class student // local class { ............... ............... //Class definition }; ............. student s1 (a); // create student object .............. // use student object }
Local classes can use global variables (declared above the function) and static variables declared inside the function but cannot use automatic local variables. The global variables should be used with the scope operator (::). There are some restrictions in constructing local classes. They cannot have static data members and member functions must be defined inside the local classes. Enclosing function cannot access the private members of a local class. However, we can achieve this by declaring the enclosing function as a friend.
54
#include <iostream.h> class List { private : double x ; // x = weight in kg, y = price of one kg. double y; public: void Setdata (double a, double b ) {x = a; y = b; } void Display ( ) ,cout<< Weight = ; cin >> x; cout<< Price = ; cin >>y; cout<< Cost of <<x<<kg at the rate of <<y<< per kg = <<x*y<<endl;}; void main() {double i,j; List *ptr= new List ; // use of new operator (*ptr).Setdata (i,j); ptr -> Display (); // (*ptr) and ptr-> are equivalent. delete ptr; }
56
#include <iostream.h> class List { private : int x,y; // x = the no of items, y = price of one item. public: void Setdata (int a, int b ) {x = a; y = b; } void Display ( ) { cout<< Number of items = ; cin >> x; cout<< Price of each item = ; cin >>y; cout<< Cost of <<x<< items at the rate of <<y<< per item = <<x*y<<endl;}; // End of class void main() { List *ptr= new List[3]; //pointer to List for (int k=0; k<3; k++) ,cout<< For item Number <<k+1<<endl; int i=0,j=0; //for user input of data (*ptr).Setdata (i,j); ptr -> Display ();} // (*ptr) and ptr-> are equivalent. delete[]ptr; }
57
REFERENCES
Reference for a variable is also an alias or just another name for the same variable. The variable name and its reference-name both point to the same block of memory where the value of variable is stored. You must note that any change in the value of reference also changes the value of variable. For creating a reference first write the type of the variable for which the reference is being created then write reference operator (&) followed by the name or identifier for the reference. Name of reference may be decided in the same way as it is done for any variable.
58
#include <iostream.h> int main() {int n = 100 ; double Weight = 35.6; char ch = S; int& Count = n ; // Count is a reference to n. double& W =Weight; // W is a reference to weight. char& T = ch; // T is reference to ch. cout<<n = <<n<< \t&n = <<&n <<\n; cout<<Count = <<Count<< \t &Count = <<&Count << endl; cout<< Weight = <<Weight << , &Weight = << &Weight<<\n; cout<< W = << W<< \t &W = << &W<<\n\n; cout<<ch = <<ch <<\t T = << T <<endl; T = Z; n = 50; //The value of reference n is changed to 50 W = 12.5; // The value of reference W is changed to 12.5 cout<< n = <<n << \tCount =<< Count <<endl; cout << W = << W<< \tWeight = << Weight << endl; cout << ch = << ch << \t T = << T << endl; return 0; } 59
NESTED CLASSES
A class may be declared inside another class. The access specifiers work on nested class in the same way as they act on other functions. In the following illustrative program class Z is declared in class Y in the public domain and class Y is in turn is declared in class X in public domain. All the three classes have private data for which appropriate constructor functions are provided in each class. The objects of each of these are declared in the main() and values assigned to them.
60
#include <iostream> using namespace std; class X {private: int x ; public: X (int a ) {x = a;} int getx () { return x ;} class Y // nested class Y declared in class X {private: int y; public : Y( int b ) {y = b;} int gety (){return y ;} class Z // class Z declared in class y { private: int z ; public : Z (int c ) { z = c;}
61
int getz () { return z;} }; // end of class Z }; // end of class Y }; // end of class X int main() { X x_object (5); X::Y y_object (10); X::Y::Z z_object (20); cout<<x_object = <<x_object.getx() <<endl; cout << y _object = << y_object.gety()<<endl; cout<< z_object = <<z_object.getz()<<endl; return 0 ; }
62
63
The inlining does not work for the following situations : 1. For functions returning values and having a loop or a switch or a goto statement. 2. For functions that do not return value and having a return statement. 3. For functions having static variable(s). 4. If the inline functions are recursive (i.e. a function defined in terms of itself). 1. 2. 3. 4. The benefits of inline functions are as follows: Better than a macro. Function call overheads are eliminated. Program becomes more readable. Program executes more efficiently.
64
Function Overloading
Function overloading is the process of using the same name for two or more functions. The secret to overloading is that each redefinition of the function must use either different types of parameters or a different number of parameters. It is only through these differences that the compiler knows which function to call in any given situation
66
#include <iostream.h> int myfunc(int i); // these differ in types of parameters double myfunc(double i); int main() { cout << myfunc(10) << " "; // calls myfunc(int i) cout << myfunc(5.4); // calls myfunc(double i) return 0; } double myfunc(double i) { return i; } int myfunc(int i) { return i; }
67
68
Garbage collection
Garbage collection is an automatic memory management feature in many modern programming languages, such as Java and languages in the .NET framework. In older programming languages, such as C and C++, allocating and freeing memory is done manually by the programmer. Memory for any data that can't be stored within a primitive data type, including objects, buffers and strings, is usually reserved on the heap. When the program no longer needs the data, the programmer frees that chunk of data with an API call. Because this process is manually controlled, human error can introduce bugs in the code. Memory leaks occur when the programmer forgets to free up memory after the program no longer needs it.
69
70