0% found this document useful (0 votes)
4 views43 pages

Objects and Classes

This document provides an overview of classes and objects in C++, detailing their definitions, member functions, and access rights. It includes examples of class declarations, object creation, and the use of arrays within classes. Additionally, it covers member function definitions, nesting of functions, and practical programming examples to illustrate these concepts.

Uploaded by

jaankirita
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
4 views43 pages

Objects and Classes

This document provides an overview of classes and objects in C++, detailing their definitions, member functions, and access rights. It includes examples of class declarations, object creation, and the use of arrays within classes. Additionally, it covers member function definitions, nesting of functions, and practical programming examples to illustrate these concepts.

Uploaded by

jaankirita
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
Objects ANd Clase —_——— 8.1 8.2 Introduction The concepts of class and object were explained in Chapter 1. Itneeds to DE strecs here that classes are the fundamental core part in an object-oriented Program, A class is a user defined datatype which holds both the data and functions The internal data of a class is called member data (or data member) and the functiong are called member functions. The member functions mostly manipulate the interna data of a class. The variables of a class are called objects or instances of a Class On completion of this chapter, you will be able to: Create a class. Define member functions in the class. Use scope resolution to define functions belonging to a class. Use arrays as class members. Use arrays of objects. Define member functions which pass and return objects. Yecialé and Initialise static data members. Study access rights of static member functions. Write friend functions, a 5 a Create objects. oa a 0 Class Declaration * fas isan aggregation of data members and data functions joined under 4 com Ss Specilier. The format ot class declaration is given below : [240) class {| : | | private : variable declarations; | functions declaration, public : variable declarations; function declarations; ass is a keyword and is the user defined name of the class. The oe Jass begins with an opening brace ( {) and ends with a closing brace { }) eenion() The term ‘private and ‘public’ are called visibility mode. The en oe indicates that members specified below the word private cannot be a utside the class. They can be accessed by the member functions eae The private brings out the data hiding feature of the object-oriented at By default, the members of a class are private. * iblic members may be accessed from anywhere within the class and even en the class. This binding of data and functions together into a single class gies referred to as encapsulation. The access to private and public members HA class is well explained diagrammatically in fig. 8.1. wher CLASS. Private Not accessible from outside class | Accessible from Data or i outside class Functions | FIGURE 6.1 [241] Example 8.1 Consider the following declaration of a class class student f + wit roll; 11 data members int age; char name {25}: public : : void getdararvoid); 1 Functions propo, pe void display(void); iB In this example, name of the class is student. The data members oft roll and pane type integer and name of type char. The two tun Class are getdata( ) and display (). Only these functions can access the data a embers The data members are usually delared as private and member functions “ 7 By default, the members of a class are private. Therefore, there is no neon be the keyword private. Wits In C++, itis possible to declare an empty class as class sample { }; “class with no members 8.3 Objects Objects are the variables of auser defined datatype called class. They ate or in the same manner as are the built-in data types ealeg Example 8.2 student x; // object x of class student Objects can also be created when a class is defined by placing thei immediately after the closing brace. Sas Example 8.3 class sample { int a; // data members int b; // private by default public : void getdata(int x, int y); void display ( ); // functions prototype 149 This definition of class also creates the objects x and y of type sample [242 cessité Class Members cee apa tne class members thal are declared to be public can be accessed wee ytside: We may access them using following syntax : re reckname . member-name; Obi (@ bject-name function-name (actual-arguments); ) 4 ple 8: ' class sample int a, b; public + int ¢; void sum( )s K main( ) i sample x; need M accessing the data member xa = 4; //error, access denied because a is a private member. x. sum( )j // accessing the member function } Defining Member Functions Member function may be defined in two places 1. Outside the class definition. 2, Inside the class definition 1. Outside the class definitions : Here we first of all define the prototype of function within the class and then define them outside using the following syntax: | retw ‘name (arguments list) | The ype of member function arguments must exactly match with the types declared in the class definition of the class-name. The Scope resolution oo (:) is used along with the class name in the header of the function “nition. it identifies the function as a member of a particular class. Example 8.5 | class sample t int a,b; public : void sum( ); hk sample : : sum( } { cout << "Sum is " include class sample { \ int a; int b; (244) inte; public : void getdataint, int); function to set the value of a,b void putans(); Ufunction to write result void sum()s function to compute sum c=avb jy Mend of class definition IhouweMember functions definition void sample :: getdatatint i, int j) { ‘ azi; bay } void sample :: putans() coute> roll >> name >> age; } void student :: display( ) { cout << roll << name << age; ) main( ) t student s1, s2, s3; } Tafay °M€8.2 shows the memory allocated to the objects s1, s2 and s8. [283] , tna) agin) stil \ 1 ‘shname slap FIGURE 8.2 8.13 Static Data Member Static data members are data objects that are common to alll objects Olag They exist only once in all objects of this class. The Static members are the information is to be shared. They can be public or private data, The stati, hea member should be created and initialised before the main function Conta bg, begins. For example, the following program segment shows how to declare the static, a member; class sample { int a, b; static int total; // static data declaration public : void getdata( ) void display( ); int sample :: total =0; 1! static data definition main ) { [264] Properties of Static Data Memb static data member is declared. nly one copy of that ‘Whenever @ ' member is created for the entire class and is shared by all the objects of that class. ber should be created and initialized before the The static data mem! ; main( ) function. By default, static data member is initialized to zero when the first : object of its class is created, 4, The access tule of static data member is same as the other data members of the class. For example, when a static data member is declared private, the non-member functions can not access this member. advantage of using a static data member is to declare the global data in ta iid be updated while the program lives in the memory. whieh shoul example 8.17 Consider the following program which illustrates the use of static data member count. finclude | finclu.e include class sample static int count; //declaration of static data number () J; Hend of aa definition int sample count; static data definition | ii far itialis | void sample :: display () initialise 0, by default | | ublic: Pe oid dsplay(); ount; cout << “value of count = “ << count << endl; | | void main() | | } | fun: l| ue of count = I || Vain gested || La Value of count = 3 ee [265 i tis com From the program, it is clear that static data member count TON to three objects. Ii initialized to 0, by default, when the objects are createg yal th, also give the initial value on Can int sample :: count = 50; When first object C1 accesses the function display( ), then value of stay me is incremented by 1 and it displays a message, when Second object C2 a bey the function display(), then the current value of static member iS again incre, S595 by 1 and it becomes 2. It shows that static data member is common to all ob 'f we had used an ordinary data member - as opposed to a static data Mem " Count, then output would have been ber fog Value of count = 1 Value of count = I Value of count = 1 Figure 8.3 shows how static members compare with ordinary data member __—_—_———— | Object 1 Object 2 Object 3 (Common to all three objects) | a cr ecaame FIGUREB3 SS Beatle Member Functions © Can also declare fineion tee ao peed function as Static by Prefixing static before the deta meni The ee oe Static member functions are same as the static independent tar object, "ber functions are common to the class and (266) Pca el ae ee ke _ Astatic function can 1 ember of the class unetion is independent of any object. Therefore, a 2 Astatic member ft static function can be called using the class name instead of its objects as follows : class—name : access and manipulate only on static data + static_function_name; he program below to understand the static member functions. totus Jook att! example 6.18 proGRAM a — include Ainclude Hinclude <[Link]> | class account | H tatic int count; i| public: static void display() static member function ' count++; cout << “The value of count=” << count << endl; i 50; static data definition int account :: count = void main() account obj, 0bj2; clrser( ); vaccount :: display(); accessing static fanction account obj3; | 1 account :: display(); i getch( ); 8.15 Constant Member Functions We can also declare a member function as a constant memb f er ensure that the member function does not alter the values Pee etn th have to be cautious to ensure thatthe datas not comupted resi can declare a member function to be constant. UH pony ig * s Example 8.19 | #include #include I class date { int day; int month; | int year; public : 7 Beldata(int a, int bint c) 1 Define function } I void display (void) const // Define const function i couts< “Date is “<< day <<” ce “ ro month <<» « } Js Mend of class definition ( void main() { date birthday; elrscr( ); [Link](15, 11, 19); [Link](); ; sgetch( ); | || Run: | Date is 15-11-19 | be Sees ___] [el 8.16 Friend Function In object oriented programming, data members declared as private in a class@ restricted from access by non-member functions. Any attempt made direct ® access these members, will result in an error message during complation. "= ‘one way to access a private data member is to change a private data re public gtoup. But this goes against the concept of data hiding and data encaps (268) —— ay'0 access the private data by non-member function is the use of frend patel a friend function, although not a member function, has full access right to tin members of the class. We can declare a function to be a friend of a rin the class spectfication by using the keyword ‘friend’ as given in following Wi 8.20 class sample { public: friend void abe( ); Md abe() “individual or non member function { } 11 body of the function ee cree omicu Mura lL They are not in the scope of a class. They are not called using object of that class. They cannot access member functions directly rather makes the use of objects of that class. They may be declared as friend in any part (private or public) of the class. They can be invoked like a normal function without the help of any | object. Usually, they have the object as arguments. Example 8.21 PROGRAM finclude Finclude | class abe | int a, b; public: sree sety() , [269] pie in uae x Meclaration of friend fay Fe sum(abe x) Hfriend function definition mm ea (xa + xb): 1 id main) abe s; celrser( ); .setv(); pee sums); Healling friend function getch( ); J | Run 65 — Note that friend function, to access the private members of the clas object as argument. Les, 8.16.1 Defining Member Function of a Class as Friend Function The friend function can also be defined within the scope of a class ton Previous program can be rewritten as tse, PROGRAM include #include class abe int a, b; yublic: void setv() 4-20; b=45; {friend int sum(abe x) /definition of friend function return(x.a + x.b); h void main() abe s; clrsee( )s sisetv()> cout << sum(s); Healling friend function etch); (270) of one class can be friend functions of another class. In such ms . ye and using the scope resolution operator as given below { oe class OMe t public: int sum); 11 member function of one kK class 1¥0 { public : friend intone :: sum();—M function sum ) of one. B The function sum( ) is a member of class one and a friend of class two. 42 Friend Class itis also possible to declare all the member functions of one class as the friend ‘unations of another class. In such cases, the class is called a friend class as given below : class three { friend class one; Vall function of - / one are friends h M10 three Aron . oA ene function can be friendly with one or more classes. When a function itor to have friendship with more than one class, the friend classes should 'ard declaration as it needs to access the private members of both classes. Thefollowi thea ing program illustrate the use of the friend function which is friendly to two R71} es Example 8.22 PROGRAM include include : class two; /iforward declaration class one int m; public: void getdata() { cout << “\nEnter the value for m : “; cin >> m; friend int sum(one,two); J; Tend of class one definition class two { int n; public: void getdata() { cout << “Enter the value for n : “; i cin >> n; | friend int sum(one,two); Js Mend of class two | int soe, Mdfiition of friend function | \| } return(a.m + bn); ‘main() one x; | two ys | celrsert ); \| [Link](); i [Link](); cout << “Sum = “< Zyass student ( rll Mar name|201 iblic? . m noid getdata(void); id display(void); rend void swap(student&, student&); ii void student : getdata(void) € gut << “Enter rollno.: “; cin >> roll; cout << “Enter name : “; cin >> name; } void student :: display(void) << roll << “Wn”; f cout << “Roll no. << mame << “\n”; cout << “Name = } void swap(student& sI, studenté& s2) Hobjects as argument Wit is friend function : student temp = sl; s] = 82; §2 = temp; } | void main() { student stul, stu2; elrser( ); cout << “\wEnter data for student 1” << “\n”; [Link](); cout << “Enter data for student 2” << “\n”; [Link](); cout << “After calling function swap()\” swap(stul, stu2); cout << “data for student 1 is \n”; stu L display(); cout << “data for student 2 is Ws | [Link](); | j getch( ); j 3. PROGRAM [r {| #include #include include class sample int x; public: void getdata(int a) | x=a; {| } | void display() t cout << x; } friend sample sum(sample a, sample 6) friend faye, Js Wend of class definition ‘ction sample sumsampe a, sample 6) Mfrend function dt sample c; ex = ax + ba; return(c); void main() {| sample obj1,0bj2,0bj3; I] clrser( ); I [Link](10); value of objl.x becomes 10 [Link](20); —/value of obj2.x becomes 20 | obj3 = sum(objl, obj2); Hobj3.x becomes objl.x + obj2.x I cout<< “Sum = “ ; | [Link](); | If getch( ); | 8.17 Local Classes It is possible to define and use a class inside a function. Such a class is cae local class. Local class can be accessed only in the body of that function. Itcann® be accessed by the outside of the function, [276] —— void fund (int a, int b) ( class sample Mocal class } classes can not use local variables declared inside the function, but can use Loca! Jes declared above the function, goo variable: ample 8.24 wile @ program to illustrate how to use local class finclude include | void sample (void) | class local 1! local class ] we. 1 void display ) | i | coutc<"Example of local class": I ; | hi } local obj; | obj. display( ); | } void main( ) sample (); IW calling the function | etch) Run: | Example of local class l| [277] ' - —E 8.18 Global Classes Global class is a class that is dined outside of any functign Pa ‘everywhere of the program Meany, , Example 8.25 Ainclude #include { class global // global class { public : void display( ) { cout<<" Exampl | POF lob cia, \| u h | | void main( ) | \ ( \ global obj; | obj, display( ); | getoh (); } Run: Example of global class 8.19 Empty Classes A class which does not have any data member and member function is know'ss empty class. A empty class's Object will take only one byte in the men) Since class does not have any data member it will take minimum memory 80 (278) — 4g = ope 826 pe finclude Hinclude Ainclude class demo [ M void main( ) demo obj; cout << "size of empty class's object : "<

You might also like