Presentation is loading. Please wait.

Presentation is loading. Please wait.

Welcome to Classes and Objects Prepared By Prepared By : VINAY ALEXANDER ( विनय अलेक्जेण्डर )TGT(CS) KV JHAGRAKHAND.

Similar presentations


Presentation on theme: "Welcome to Classes and Objects Prepared By Prepared By : VINAY ALEXANDER ( विनय अलेक्जेण्डर )TGT(CS) KV JHAGRAKHAND."— Presentation transcript:

1 Welcome to Classes and Objects Prepared By Prepared By : VINAY ALEXANDER ( विनय अलेक्जेण्डर )TGT(CS) KV JHAGRAKHAND

2 Introduction Classes Data hiding and Encapsulation Functions in a class Using objects Static Class Members

3  The most important features of C++ are the classes and objects. C++ is a bunch of small additions to C, with a few major additions. As the name object-oriented programming suggests this approach deals with objects. Classes are collections of related to a single object type. Classes not include information regarding the real world object but also function to access the data and classes possess the ability to inherit from other classes

4  Class represents a group of similar objects  A class is a way to bind the data describing an entity and its associated functions together  A class is user-defined data type used to implement an abstract object giving you the capability to use object oriented programming with c++.  A class includes members  A member can be either data, know as a data member or a function known as a member function

5 5  Class definition  Tells the compiler what member functions and data members belong to the class.  Keyword class followed by the class’s name. {}  Class body is enclosed in braces ( {} )  Specifies data members and member functions :  Access-specifier public:  Indicates that a member function or data member is accessible to other functions and member functions of other classes.

6 class class_name { Private: data_members; member_functions; public: data_members; member_functions; protected: data_members; member_functions; };

7  The contents of each instance of class_name : data_members and data_functions  The members are of private, protected or public specifier

8  The declaration of a class involves declaration of its four associated attributes 1) Data members are the data-type properties that describe the characteristics of a class. There may be zero or more data members of any type in a class 2) Member functions are set of operations that may be applied to object of that class. There may be zero or more member functions of a class. They are referred to as the class interface 3) Program Access Levels that control access to members from within the program. These access levels are private, protected or public.Depending upon the access level of a class member, access to it allowed or denied 4) Class Tag name that serves as a type specifier for the class using which objects of this c lass type can be created.

9  The class specification takes place in two parts =>Class definition: which describe the component members (data member and functions members) of the class =>Class method definition : which describe how certain class member function are implemented.

10 =>Outside the class definition =>Inside the class definition

11  A member function definition outside the class definition is much same as that of function definitions. The only difference is that the name of the function is the full name of the function. the full name (also called qualified-name) of the function is written as:  Class-name::function-name  Class-name:indicate that the function specified by function_name Is a member of the class specified by class-name.  The symbol :: called the scope resolution operator specifies that the scope of the function is restricted to the class class-name

12  The general form of a member function definition outside the class definition is Return-type class-name :: function_name (parameter list) { Function body } Membership label:  The membership label (classname ::) will resolve their identity and scope Void student : : add ( )

13 class salesman { int salesman_no: int product_no; Public: void readdata( ); void displaydata( ); }; void salesman::readdata( ) { cout<<“enter salesman_no”; cin>>salesman_no; } void salesman::displaydata( ) { cout<<“the salesman_no”<<salesman_no; }

14 A function define inside a class is automatically inline function. class student { int a; Public: void readdata () { cout<<“enter the value of a”; cin>>a; }

15  A class specification does not define any objects of its type rather it just define the properties of a class example  Student s1,s2,s3 ;

16 =>The private data of a class can be accessed only through the member function of that class =>The public data can be accessed by the non- member function through the objects of that class. =>The public member function of a class are called by non-member functions using the object. =>objec-name.function-name(actual-arguments);

17 class abc { int x,y // private by default Public: int z; int add (int a,int b) { int c=a+b; return c; } }; abc a1,a2;

18  The general format for calling a member function is Object-name.function-name(actual-arugment); a1.add(2,3); a2.add(4,6);

19  To access the public data member,the format used is: a1.z or a2.z But if we give a1.x or a2.y An error since x and y are private data member of class abc

20  An array in a class can be private or public data member of the class  A class can have an array as its member variable  If an array happen to be private data member of the class then only the member functions of the class can access it.  If an array is a public data member of the class it can be accessed directly using object of this class type.

21 A class can have an array as its member variable. An array in a class can be private or public data member of the class. If an array happens to be a private data member of the class, then, only the member functions of the class can access it. On the other hand, if an array is a public data member of the class, it can be accessed directly using objects of this class type. For example - Class ABC { int arr [10]; // private by default public : int largest (void); int sum (void); }; Here the variable arr[10] is a private data member of the class ABC. It can be accessed only through the member function largest ( ) & sum ( ).

22 Class exarray { Int arr[10]; //private data member Public: Int largest(void); Int sum(void); }; The data member of class exarray accessed only through the member function largest() and sum(); not directly by objects.

23  There are three access types that determine the scope of Class & its members – public, private and protected.  The public access specifier states that anything following this keyword can be accessed from outside this class.  The Private members are the class members that are hidden from the outside world. The private members implement the OOP concept of data hiding. The private members of a class can be used only member functions of the class in which it is declared.

24 =>The protected access specifier plays its role in inheritance i.e. when the new class is derived from the existing class. Protected members are the members that can be used only by member functions and friends of the class in which it is declared.The protected members are similar to private members. The only difference between protected and private is that protected members are inheritable while private members are non-inheritable.

25 NoYes Protected No Yes Private Yes Public Object Subclass Class Access Permission Access Specifier

26 #include class x { private: int a; int sqt(a) { retutn a*a; } Public: int b; int twice(int i) { return 2*i; } int tsq(int i) { int p=sqr(i); int q=twice(p); return q; } }; X obj1; void main( ) { obj1.b=5; obj1.a=2; //wrong obj1.twice(10); obj1.sqr(10); obj1.tsq(10); }

27 #include Class customer { private: char cust_name[25]; char address[25]; char city [15]; double balance ; public :void input_data(void) {cout<<“Enter the Name “; gets (cust_name); cout<<“Enter Address”; gets(address); cout<<“Enter City”; gets(city); cout <<“Balance”; cin >>balance; } void print_data (void) { cout<<“\n Customer Name “<<Cust_name; cout<<“\n Address”<<address; cout<<“\n City “<<city; cout<<“\n Balance”<< balance ; } }; void main( ) { customer cust; cust.input_data(); cust.print_data(); }

28  Global Class– A Class is said to be global if its definition occurs outside the bodies of all functions in a program, which means that object of this class type can be declared from anywhere in the program. #include Class X // Global class type X {…………..} ; X obj1; // Global object obj1 of type X int main( ) { X obj2;// Local object obj2 of type X };  Local Class – A class is said to be local if its definition occurs inside a function body, which means that objects of this class type can be declared only within the function that defines this class type. for Example - #include ------------- int main ( ) { Class Y { ………… }// Local class type Y Y obj1; }; // Local object obj 1 of type Y void fun(void) { Y obj; // invalid. Y type is not available in fun( ) }

29 SCOPE OF PRIVATE AND PROTECTED MEMBERS =>The private and protected members of a class have class scope that means these can be accessed only by the member function of the class. These members cannot be accessed directly by using the object. =>Scope of public members: The scope of public members depends upon the object being used for referencing them. If the referencing object is a global object, then the scope of public members is also global and if the referencing object is a local object, them the scope of public members is local

30 1.Accessor /getter – are used to read values of private data members of a class which are directly not accessible in non-member function. However, accessor function do not change the value of data members 2.Mutator / Setter – These functions allow us to change the data members of an object. 3.Manager function – These are specific functions e.g. (Constructor and destructor) that deal with initializing and destroying class instances. Why Accessor / Mutators – Because by providing accessor and mutator we make sure that data is edited in desired manner through a mutator.further if a user wants to know current value of a private data member, he can get it through an accessor function.

31 Class student {int rollno; char name[25]; float marks; char grade; public: void read_data(); void display_data(): int get rollno() { return rollno; } float get marks() { return marks; } // accessor methods they have the return type. void calgrade() { if marks>= 75 // Mutator method it is modyfying data member grade grade = ‘A’ else if marks >= 60 grade= ‘B’ else if marks >=45 grade = ‘C’ } };

32 =>Nested classes: A class declared within another class is called a nested class. The outer class is known as enclosing class and the inner class is known as Nested class. => Data Hiding and Encapsulation: Class->encapsulation Private and protected members->Data hiding Public members->abstraction

33 1. INLINE FUNCTION :- These functions are designed to speed up programs. The coding of these functions are like normal function except that inline function’s definitions start with the keyword “inline”. The other distinction between normal function and inline function is the different compilation process for them.  Inline functions run a little faster than the normal function.  Inline function provide an alternative. With inline code the compiler replaces the function call statement with the function code itself ( this process is called expansion) and then compiles the entire code.  Thus, with inline functions the compiler does not have to jump to another location to execute the function. Declaration : inline void max (int a, int b) { cout b?a:b); } void main ( ) { int x,y ; cin >> x >> y; max (x, y); }

34 In the above code the function max( ) has been declared inline, thus, it would not be called during execution. Rather its code would be inserted into main ( ) and then complied.  An inline function definition should be placed above all the functions that call it. The function should be inline only when they are small.  The inline function does not work for following situations –  For functions that return values  For functions having loop, switch or goto  For have return ( )  If function contain static variables or is recursive.  The member function of a class,if defined, within the class definition, are inlined by default. We need not use keyword inline.

35 => Constant Member functions: If a member function of a class does not alter any data in the class, then this member function may be declared as a constant member function using the keyword const. Example: int maxi(int, int) const; void prn(void) const; The qualifier const appears both in member function declarations and definitions.

36 =>Nesting of Member Functions: When a member function is called by another member function, it is called nesting of member functions. => The 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. : : variable-name This operator allows access to the global version of a variable.

37 #include<iostream.h>#include<conio.h> int m = 10; // global void main( ) { int m = 20; //local int m = 20; //local clrscr( ); clrscr( ); cout << "m_local = " << m << "\n"; cout << "m_local = " << m << "\n"; cout << "m_global = " <<::m << "\n"; cout << "m_global = " <<::m << "\n"; getch( ); getch( );} m_local = 20 m_global = 10 m_local = 20 m_global = 10

38  The declaration of m declared in the main function hides the integer named m declared in global namespace scope. The statement ::m = 10 accesses the variable named m declared in global namespace scope.  Note: If there are multiple variables of the same name declared in separate block then the :: operator always refers to the file scope variable.

39 =>Using object: when a class has been defined, its objects can be created, using the class name as type specifier. Example: class-name object name(comma separated); => Memory allocation of objects: Member functions are created and placed in the memory space only once when the class is defined. The memory space is allocated for objects,data members only when the objects are declared. No separate space is allocated for member functions when the objects are created.

40 An array having class type elements is known as Array of objects. An array of objects is declared after the class definition is over and it is defined in the same way as any other type of array is defined. For example - class item { public: int itemno; float price; void getdata (int i, float j) { itemno=I;price=j;} }; item order[10]; Here the array order contains 10 objects. To access data member itemno of 2 nd object in the array we will give = order[1].itemno; // for more detail see program 4.4 of text book.

41 OBJECTS AS FUNCTION ARGUMENTS : An object may be used as a function argument in two ways –. 1.A copy of the entire object is passed to the function. // by value. : When an object is passed by value, the function creates its own copy of the object and works with its own copy. therefore, any changes made to the object inside the function do not affect the original object.

42  2.Only the address of the object is transferred to the function. // by reference. : When an object is passed by reference, its memory address is passed to the function so that the called function works directly on the original object used in the function call. thus, any changes made to the object inside the function are reflected in the original object as the function is making changes in the original object itself.

43 =>Functions Returning Objects: Objects can not only passed to functions but function can also return an object.

44 1.Static Data Member - a static data member of a class is just like a global variable for its class. That is, this data member is globally available for all the objects of that class type. The static data members are usually maintained to store values common to the entire class. Declaration of static data member : class X. { static int count ; // within class. }; int X :: count ; // for outside class. A static data member can be given an initial value at the time of its definition like – int X :: count =1 0;

45 2.Static Member Function - A member function that accesses only the static members of a class may be declared as static. class X. { static int count ; // within class. static void show (void). { cout <<“count”; }; }; int X :: count ; To call the static function show( ) of above defined class X we will give = X::show ( ); //for more detail see program 4.8 of text book.

46 =>A static data member is different from ordinary data member of a class as- =>There is only one copy of static data member maintained for the entire class which is shared by all the objects of that class. 1. It is visible only within the class, however, its life time is the entire program. =>A static member function is different from ordinary member function of a class as- 1. A static member function can access only static members of the same class. 2. A static member fuction is invoked by using the class name instead of its objects as - Class name :: function name X::show ( ); for more detail see program 4.8 of text book.

47 1. Define a class Book with the following specification : Private members of the class Book are – Book_No integer,Book_Title 20 char, Price float, (price per copy) Total_Cost ( ). A function to calculate the total cost for N numbers of copies, where N is passed to the function as argument. Public members of the class Book are – INPUT( ) function to read Book_No,Book_Title, Price. PURCHASE() function to ask the user to input no. of copies to be purchased. It invokes Total_Cost( ) & prints the total cost to be paid by the user. 2. How does a class accomplish data abstraction and encapsulation ? 3. What is the significance of scope resolution operator :: ? 4. How are data and function organized in Object Oriented Programming ? 5. When will you make a function inline and why ?

48 Class Book { int BOOK_NO; char BOOK_TITLE[20]; float PRICE; float TOTAL_COST (int N) { float TOTAL ; TOTAL= N* PRICE; return TOTAL; } public: void INPUT() { cout<<“Enter Book No,:”; cin >>BOOK_NO.; cout <<“Enter Book Title:”; gets(BOOK_TITLE); cout <<“Enter Price:”; cin >> PRICE; } void PURCHASE() { int a; float TOT; cout <<“Enter the no. of copies to be purchased:”; cin >>a; TOT= TOTAL_COST(a); cout <<“ Total Amount is :”<<TOT; } };

49 Define a class TEST in C++ with following description: Private Members TestCode of type integer Description of type string NoCandidate of type integer CenterReqd (number of centers required) of type integer A member function CALCNTR() to calculate and return the number of centers as (NoCandidates/100+1) Public Members A function SCHEDULE() to allow user to enter values for TestCode, Description, NoCandidate & call function CALCNTR() to calculate the number of Centres A function DISPTEST() to allow user to view the content of all the data members

50 class TEST { int TestCode; char Description[20]; int NoCandidate,CenterReqd; void CALCNTR(); public: void SCHEDULE(); void DISPTEST(); }; void TEST::CALCNTR() { CenterReqd=NoCandidate/100 + 1; } void TEST::SCHEDULE() { cout >TestCode; cout<<”Description :”;gets(Description); cout >NoCandidate; CALCNTR(); } void TEST::DISPTEST() { cout<<”Test Code :”<<TestCode<<endl; cout<<”Description :”<<Description<<endl; cout<<”Number :”<<NoCandidate<<endl;; cout<<”Centres :”<<CenterReqd<<endl;; }

51 Marking Scheme: (Total 4 marks) (1 Mark for correctly declaring Data Members) (1 Mark for correctly defining CALCNTR()) ( ½ Mark for correctly defining SCHEDULE()) ( ½ Mark for calling CALCNTR() from SCHEDULE()) ( ½ Mark for correctly defining DISPTEST()) ( ½ Mark for correct syntax of class)

52  Q1 what is the significance of scope resolution operator (::) ?  Q2 what is difference between private and public member of a class ?  Q3 Define abstract data type and encapsulation ?  Q4 Declare a class employee having following members: Data member: employee number Employee name Employee address Employee department Member function To read data member To display

53


Download ppt "Welcome to Classes and Objects Prepared By Prepared By : VINAY ALEXANDER ( विनय अलेक्जेण्डर )TGT(CS) KV JHAGRAKHAND."

Similar presentations


Ads by Google