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

C++ Unit 1

Uploaded by

jpf0b
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)
35 views43 pages

C++ Unit 1

Uploaded by

jpf0b
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
You are on page 1/ 43
Shree Swaminarayan College c of Computer Science % “¥ Bsc i+ $ a + + Unit -1 Fundamental of Programming and QOP Concept ' PREPARED BY: MADHAYV K. DAVE « Shree Swaminarayan College of Computer Science**¥z 4 B.Sc. IT - 3 CC-304, Programming in C++ Jun} = 5 Basic Concepts of Object Oriented Programming ? It is necessary to understand some of the concepts used extensively in object — oriented programming. These include: (1) Objects 2) Classes @) Encapsulation (4) Data Abstraction (8) Inheritance (6) Polymorphism (7) Dynamic Binding (8) Message Passing 1. Objects:- \ * Objects are the basic run-time entities in an object — oriented system. They may represent a person, a place, a bank account, a table of data or any item that the program has to handle. ‘ They may also represent user defined data such as vectors, time and lists. ‘ Programming problem is analyzed in terms of objects and the nature of communication between them, “+ Program objects should be chosen such that they match closely with the real-world objects. * Objects take up space in the memory and have an associated address like a record in Pascal, or a structure in C. ‘+ When a program is executed, the objects interact by sending messages to one another. 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 other's data or code, It is sufficient to know the type of message accepted, and the type of response retuned by the objects. Although different authors represent them differently. below figure shows ‘wvo notations that are popularly used in object-oriented analysis and design, Prepared By: - Madhav K. Dave (SSCCS, Bhav Page 1 of 42 of Computer Science”4° 7°92 < (a) ‘ y rs DATA Name Date-of-birth Marks FUNCTIONS Total Average Display 2. Classes:- ta. The entire set of data and code “Object contain data, and code of an object can be made a user-defined data type with the help of class. In fact, to manipulate that dat objects are variables of the type class. Once a class has been defined, we can create any number of objects belonging to that Jass with which they are created. class. mango, apple and Each object is associated wit ‘A class is thus a collection o} orange are members of the class Classes are user-defined data programming language. If fruit has been defined as a class, fruit mango; ate an object mango belonging to the class fruit. template. It specifies what data and what h the data of type cl objects of similar type. For example, fruit. types and behave like the built-in types of @ then the statement is : will cre ‘A class serves as a blueprint or a plan or a be included in objects of that class. s its format and behavior by defining a class. For example, fined data type to represent dates. The compiler and the functions will “The programmer define there can be a user-de! computer do not know about dates. ‘Programmers have to define the behavior of dates by designing a date class. This class expresses the format of date and the operations that can be performed on it. Prepared By: - Madhav K. Dave (SSCCS, Bhavnagar) Page 2 of 42 < EO Shree Swaminarayan College of Computer Science> CC-304, Programming in C++ 3. Encapsulation: The wrapping up of data and functions into a single unit (called class) is known as Encapsulation. Encapsulation is a programming mechanism that binds together code and the data it manipulates, and that keeps both safe from outside interference and misuse. Data 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. In an object-oriented language, code and data can be bound together in such a way that a self-contained black box is created. Within the box are all necessary data and code. ‘When code and data are linked together in this fashion, an object is created. In other words, an object is the device that supports encapsulation. Data Abstraction:- Abstraction refers to the act of representing essential features without including the background details or explanations. Classes use the concept of abstraction and are defined as a list of abstract attributes such as size, weight and cost, and function to operate on these attributes. ‘They encapsulate all the essential properties of the objects that are to be created. ‘The attributes are sometimes called data members because they hold information. The functions that operate on these data are sometimes called methods or member functions. Since the classes use the concept of data abstraction, they are known as Abstract Data Types. Inheritance:. Inheritance is the process by which objects of one class acquire the properties of objects of another class. + Using a concept called inheritance new classes can be built from the old ones. “ The new class referred to as a derived class, can inherit the data structures and functions of the original class, or the base class. The new class can add data elements and functions to those it inherits from its base class. Prepared By: - Madhav K. Dave (SSCCS, Bhavnagar) Page 3 of 42 ae See Shree Swaminarayan College o ic pse.IT=3" (onic sion. For example, the bird ‘robin’ is a CC-304, Programming In CHF ‘concept of hierar whicl tical classific Jn is again a part of the cla his sort of division is that each derived class a ne Jass from which it is derived as illustrated in below figure. sss ‘bird’. 2 ‘It supports the ie part of the class ‘flying bird 4p The principal behind 1 characteristics with the cl Attributes Feathers Lay eggs Attributes Attributes Kiwi Penguin Swallow Robin Attributes Attributes Attributes Attributes [Property Inheritance] ‘In OOP, the concept of inheritance provides the idea of reusability. This means that ~~ we can add additional features to and existing class without modifying it. This is possible by deriving a new class from the existing one. The new class will have the combined features of both the classes. The real application and power of the inheritance mechanism is that it allows the programmer to reuse a class that is almost, but not exactly, what he wants, and in such a way that it does not introduce any undesirable side effects into the rest of the classes. Using inheritance, an object need only define those qualities that make it unique within its class. It can inherit its general attributes from its parent. Thus, it is the Page 4 of 42 Prepared By: - Madhav K. Dave (SSCCS, Bhavnagar) Shree Swaminarayan College of Computer Science*¥4"7 B.Sc, IT=3" CC-304, Programming in C++ ni inheritance mechanism that makes it possible for one object to be a specific instance ofa more general case. 6. Polymorphism:- * Polymorphism is another important OOP concept. Polymorphism, a Greek term, means the ability to take more than one form. ‘> An operation may exhibit different behaviors 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. To exhibit different behaviors in different instances is known as operator overloading. > Figure: Circle object Box object ‘Triangle object ences 4 Above figure shows that a single function name can be used to handle different number and different types of arguments. This is something similar to a particular word having several different meanings depending on the context. > Using a single function name to perform different types of tasks is known as function overloading. <> Polymorphism plays an important role in allowing objects having different intemal structure to share the same external interface and is widely used to implementing inheritance. Prepared By: - Madhav K. Dave (SSCCS, Bhavnagar) Page 5 of 42 Swaminan json una a ceed by the phrase “one, Te to design @ generic s often expres 304. programming inc it is possibl the concept of polymorphism } je methods.” This means that elated activities. .e complexity More generally» interface, mnultipl interface to 9 group ofr 4 Polymorphism helps rede general class of action. by allowing the same interface to specify @ 7. Dynamic Binding:- ii yonse Binding refers to the linking of a procedure call to the code to be executed in resp to the call. ‘ ' . Dynamic binding (also known as late binding) means that the code associated with @ given procedure call is not known until the time of the call at run-time. Dynamic binding is associated with polymorphism and inheritance. associated with a polymorphic reference depends on the dynamic reference. ‘> Itis algorithm is, however, unique to each object redefined in each class that defines the object. At run-tims object under current reference will be called. ‘A function call type of that t and so the draw procedure will be fe, the code matching the 8. Message Passing:- 4 An object oriented program consists of a set of objects that communicate with each other. 4 The process of programming in an object-oriented languages therefore, involves the following basic steps: (1) Creating classes that define objects and their behavior. 2) Creating objects from class definitions, and G) Establishing communication among objects. é Objects communicate with one another by sending and receiving information much the same way as people pass messages to one another. % The concept of message passing makes it easier to talk about building systems that directly model or simulate their real-world counterparts. A nee for an object is a request for execution of a procedure, and therefore will invoke a function (procedure) in the receiving obj ‘ g object that generates the desi ~ a nt red result. 4+ Message passing involves specifying the name of the object, the name of th Er (message) and the information to be sent. For Example : : oe ee Prepared By: - Madhav K. Dave (SSCCS, Bhavnagar) Page 6 of 42 age 6 o! wee S Sng & Shree Swaminarayan College of Computer Science? #3" BSc. IT = 3" CC-304, Programming in C+ employee.salary (name); object information message Introduction of Function:- A function is a subroutine that contains one or more C++ statements and performs a specific task. “> Every program that you have written so far has used one function: main( ). They are called the building blocks of C+ because a program is a collection of functions. “User-defined function as one of the main building blocks of C++ programs. A function provides a convenient way of packaging a computational recipe, so that it can be used as often as required. Advantages of using functions are that it is possible to reduce the size of a program by calling and using them at different places in the program. + All of the “action” statements of a program are. found within functions. Thus, a function contains the statements that you typically think of as being the executable part of a program. In fact, a large, commercial program will define hundreds of functions. “When the function is called, control is transferred to the first statement in the function body. The other statement in the function body is then executed and control retumns to the main program when the closing brace is encountered. +> A function definition consists of two parts : Prototype(interfate) and body. + C++ function can be overloaded to make it perform different tasks depending on the arguments passed to it. © General form of a Function:- & AllC-++ functions share a common form, which is shown here: return-type func { n-name(parameter-list) J body of function Prepared By: - Madhav K. Dave (SSCCS, Bhavnagar) Page 7 of 42 SBE te Shree Swaminarayan College of Computer Science, x* B.Sc. IT-3" aa CC-304. Programming in CH ” © Main Function in C++: ‘+ In C+, the main( ) retums a value of type int to the operating system. C++, therefore, explicitly defines main() as matching one of the following prototypes : int main(); int main(int arge, char * argy[]); ‘* The functions that have a return value should use the return statement for termination. The main( ) function in C++ is, therefore, defined as follows: int main() { return 0; *® The retum type of functions is int by default, the keyword int in the main ( ) header is optional. Most C++ compilers will generate an error or warning if there is no return statement. C+ issues the warning : Function should return a value “© Many operating systems test the return value (called exit value) to determine if there is any problem. “% The normal convention is that an exit value of zero means the program runs successfully, while a nonzero value means there was a problem. The explicit use of a retum (0) statement will indicate that the program was successfully executed. e Function Prototyping:- + Function prototyping is one of the major improvements added to C++ functions. “The prototype describes the function interface to the compiler by giving details such as the number and type of arguments and the type of return values, With function prototyping, a template is always used when declaring and defining a function. % When function is called, the compiler uses the template to ensure that proper arguments are passed, and the return value is treated correctly. Prepared By: - Madhav K. Dave (SsCcs, Bhavnagar) Page 8 of 42 ‘ ‘arayan College of Computer Science? ¥4" CC-304. Programming in C++ l Any violation in matching the arguments or the return types will be caught by the compiler at the time of compilation itself. In C++, all functions must be declared before they are used. Typically, this is Accomplished by use of a function prototype. Prototypes specify three things about a function: © Its retum type © The type of its parameters © The number of its parameters + Prototypes allow the compiler to perform three important operations: © They tell the compiler what type of code to generate when a function is called, Different retum types must be handled differently by the compiler. They allow C+ to find and report any illegal type conversions between the types of arguments used to call a function and the type definition of its parameters. © They allow the compiler to detect differences between the number of arguments used to call a function and the number of parameters in the function. + The function prototype is a declaration statement in the calling program and is of the following form: ‘Syntax: - type function-name(argument. 4b The use of parameter names in a prototype is optional. The argument-list contains the types and names of arguments that must be passed to the function. Example: - float sum(float x, float y); In the function declaration, the names of the arguments are dummy variables and therefore, they are optional. That is, the form float sum(float, float); The above function prototype is acceptable at the place of declaration. At this stage, the compiler only checks for the type of arguments when the function is called. + Ingeneral, we can either include or exclude the variable names in the argument list of prototypes. 4 The variable names in the prototype just act as placeholders and, therefore if names are used, they don't have to match the names used in the function call or function definition. +> In the function definition, names are required because the arguments must be referenced inside the function. Prepared By: - Madhav K. Dave (SSCS, Bhavnagar) Page 9 of 42 ¢ Shree Swaminarayan College of Computer Science**; BSc. IT—3" : CC-304. Programming in C++ * “> For Example, float sum(float a, float b) . { float ans = atb; } ‘> The function sum() can be invoded in tha program as follows: float ans1=sum(x, y); // Function call ‘> The variable x and y are known as the actual parameters which specify’ the dimensions of ansl. Their types should match with the types declared in’ the prototype. Remember, the calling statement should not include type names in the argument list. * We can also declare'a function with an empty argument list, as in the following example: void display(void); « Call by Reference “A function call passes arguments by value. The called function creates a new set of variables and copies the values of arguments into them. “+ The function does not have access to the actual variables in the calling program and can only work on the copies of value. ‘ This mechanism is fine if the function does not need to alter the values of the original variables in calling program but there may arise situations where we would like to change the value of variables in the calling program. ~ For example, in bubble sort, we compare two adjacent elements in the list and interchange their values if the first element is greater than the second. If a function is used for bubble sort, then it should be able to alter the values of variables in the calling function, which is not possible if the call-b-value method is used. Provision of the reference variables in C++ permits us to pass parameters to the functions by reference. When we pass arguments by reference, the ‘formal’ arguments in the called function become aliases to the ‘actual’ arguments in the calling function. This means that when the function is working with its own arguments, it is actually working on the original data. Consider the following Function: & * ” Prepared By: - Madhav K. Dave (SSCCS, Bhavnagar) Page 10 of 42 a7 * See Shree Swaminarayan College of Computer Science?” BSc. IT [ean] CC-304. Programming in C+ l void swap (int &a, int &b) // a and b are reference variables { Ay “ee int t= 95 a=b; b I 4 Ifm and n are two integers variable then the function call : swap(m , n) + Will exchange the value of m and n using there aliases (referehce variables) a and b. this is accomplished using pointer and indirection as follows: void swap! (int *a , int *b) / function definition { int t5 t=*a; —_//assign the value at address ato t * // put the value at b into a *b=*t; // put the value at t into b } ‘ This function can be called as follows: swapl(&x,&y); _ //call by passing addresses of variables Return by Reference A function can also retumn a reference. Consider the following function: int & max (int &x, int &y) { if(x>y) ' { return(x); } ' return(y); Prepared By: - Madhav K. Dave (SSCCS, Bhavnagar) Page 11 of 42 ~25_.£ Shree Swaminaray@) * RY f CC-304. Programming in C++ Since the return type of main( ) is int & the fu (and not the values). Then @ function call such as either a or b depending on their value. , . ‘This means that this ‘fanetion call can appear on the left-hand side of assignment statements. That is, the statement. max(a, b) =15 ‘This is legal and assigns -1 to a ifitis lar A Inline Function i in a program is to save some memory One of the objectives of using function space, which becomes appreciable when a function is likely to be called many times. «» However, every time a function is called it takes 2 Jot of extra time in exec series of instructions for takes such as jumping to the function, saving registers, pushing arguments into the stack and returning the callirig function. “ When a function is small, a substantial percentage of execution time may be spent in such overheads. One solution to this problem is to use macro definitions, popularly known as macros; Preprocessor macros are popular in C. «> The major drawback with macros is that they are not the usual error checking does not occur during compilation. Cat has a different solution to this problem. To eliminate the cost of calls to small functions, C++ proposes a new feature called Inline Function. An Inline Function is a function that is expanded in line when it is invoked. & That is, the compiler replaces the function call with the corresponding function code (something similar to macros expansion). + The inline functions are defined as follows : puter Science? 7; n College of Com| 34 Unit rnetion returns reference to X ory max(a,b) will yield areference to * ger, otherwise -1tob. ating a really function and therefore, Syntax:- inline function-header { } funetion body Prepared By: - Madhav K. Dave (SSCCS, Bhavnagar) Page 12 of 42 of CC-304. Programming in C++ n College of Computer Sciene: m Mat Shree Swaminaray: Prepared By: - Madhav K. Dave (SSCCS, Bhavnagar) Page 13 of 42 BHO Example:- inline int mul(int x, int y) { return (x*y)3//20 main() { cout< Some of the situations where inline expansion may not work are: 1. For functions returning values, if a loop, a switch or a goto exists. 2. For functions not returning values, if a return statement exists. 3. If functions contain static variables. 4, If inline functions are recursive. Default Arguments & C+ allows us to call function 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 the function call. Default value are specified when the function is declared. The compiler looks at a i prototype to see how many arguments a function uses and alerts the programs for possible default values. Syntax: type function-name(argument-list, default-argument); 7 Shree Swaminarayan College of Computer Science»; : BSc. IT-3" CC-304, Programming in C+ Example:- int sum(int a, int b, int c=4); + The above prototype declares a default value of 4 to the argument c.A subsequent funetion call like : value = sum(5,8); // one argument missing To override default value we passes an explicit value like : value = sum(5,8,9); The default value is specified in a manner syntactically similar to a variable initialization. ‘+ A default argument is checked for type at the time of declaration and evaluated at the time of call. One important point to note is that only trailing arguments can have a default values and therefore we must add default form right to left. Some examples of function declaration with default value are: t mul (inti, intj=5,k= 10); // legal int mul (int i= 0, int j, int k= 10); // illegal int mul (int i=5, int j); H illegal Benefits of Default Argument * Default arguments are useful in situations where some arguments aly ys have the same value, For example, bank interest may remain the same for all customers for a particular period of deposit. It also provides a greater flexibility to the programmers. A function can be written with more parameters than are required for its most common application. Using default arguments, a programmer can use only those arguments that are meaningful to a particular situation. % * ‘We can use default arguments to add new Parameters to the existing functions. Default arguments can be used to combine similar functions into one. ¢ Const Arguments In C++ an arguments to a function can be declared as const as shown below: int sttrlen( const char *p); int langth (const string &s); Prepared By: - Madhav K. Dave (SSCCS, Bhavnagar) Page 14 of 42 ME Ske « Shi i a Steed ree Swaminarayan College of Computer Science? ¥4"7 A structure is a convenient tool for handin; ; : s a group of logically related data i p + Ibis a user-defined data type with a template that serves to define its dat —- . : Prepared By: - Madhav K. Dave (SSCCS, Bhavnagar) Page 16 of 42 / SSE Shree Swaminarayan College of Computer Science?“ B.Sc, IT- 3 7 CC-304. Programming in C++ [[enie—1 J % Once the structure type has been defined, we can create variables of that type using declarations that are similar to the built-in type declarations. “+ For example, consider the following declaration: t struct student { char name|20}; int rollno; float percentage; i & The key-word struct declares student as a new data type that can hold three fields of different data types. “These fields are known as structure members or elements. +> The identifiers student, which is referred to as structure name or structure tag, can be used to create variables of type student. * Foreg, struct student S; // C declaration + S is a variables of type student and has three member variables as defined by the template, Member variables can be accessed using the dot or period operator as follows:- strepy(S.name, “madhav"); S.rolino = 35; S.percentage = 75.86; ¢ Limitations of a C structure “> The standard ¢ does not allow the struct data type to be treated like built-in data types. For example, consider the following structure: struct complex { float x; float y; \ b i struct complex c1,¢2,c3; i “ The complex number cl, c2 and c3 can easily be assigned values using the dot operator but we can not add two complex numbers or subtract one from the other. For eB, Prepared By: - Madhav K. Dave (SSCCS, Bhavnagar) Page 17 of 42 of Computer Science? ¥; eo 2c 2 Shree Swaminarayan College Ge pseiT-3 CC-304. Programming in C++ eeclte2; // Its illegal imitation 0! in C Language {fc structures is that they do accessed by the structur not permit data hiding + Another important li a nembers are public structure members can be directly members. Extensions to structures C++ supports all the features of structures as defined in c. but C++ has expanded its capabilities further to suit its OOP philosophy. > It attempts to bring the user-defined types as ¢ types, and also provides a facility to hide the data of OOP. Inheritance a mechanism by which one type can inherit characteristics from other types is also supported by C++. In C++, a structure can have bot! declare some of its members as ‘private’ so that the; Jose as possible to the built-in--data which is one of the main principles .s members. It can also h variables and functions @: be accessed directly by y can not * the external functions. In C++, the structure names are stand alon In other words, the key-word struct can variables. For example, we can declare the st Student S; // C++ declaration Remember, this is an error in e. 4 C++ incorporates all these extensions in another user-defined type known as class. ‘There is very little syntactical difference between structures and classes in C++ and, therefore, they can be used interchangeably with minor modifications. a Since class is a specially introduced data type in c++, most of the c++ programmers tend to use the structures for holding only data, and classes to hold both the data functions. an be used like any other type names. e and c: leclaration of structure be omitted in the de student variable S as : ¢ Specifying a Class 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: 0 1.Class declaration ) o 2.Class function definitions 4 5 > 3 Prepared By: - Madh: a n0,02 yy: - Madhav K, Dave (SSCCS, Bhavnagar) Page 18 of 42 B.Sc. IT = 3" - CC-304. Programming in C++ [Lunit—3 | ~- Shree Swaminarayan College of Computer Science*¥7~ The general form of a class declaration is: class class-name { private: data member; member function; public: data member; member function; The class declaration is similar to a struct declaration. The key-word class specifies that what follows is an abstract data of type classname. The body of a class'is enclosed within braces and terminated by a semicolon, The class body contains the declaration of variables and functions. These functions and variables are collectively called class members. They are usually grouped under two sections, namely, privates and public to denote which of the members are private and which of them are public. The key-words private and public are known as visibility labels. Note that these key- words are followed by a colon. The class members that have been declared as private can be accessed only from within the class. On the other hand, public members can be accessed from outside the class also. The data hiding (using private declaration) is the key feature of object-oriented programming. ‘The use of the key-word private is optional. By default, the members are private. Such a class is completely hidden from the outside world and does not serve purpose. The variables declared inside the class are known as data members and the functions are known as member functions. i Only the member functions can have access to the private data members and private functions. However, the public members (both functions and data) can be accessed from outside the class. The binding of data and functions together into a single class-type variable is referred to as encapsulation. A simple class example:- Prepared By: - Madhav K. Dave (SSCCS, Bhavnagar) Page 19 of 42 . oe ee ience* 75-34 # [ou , ge of Computer Se vd eee te Shree ‘ * \ CC-304. Programming in C++ % A typically class declaration would look like: class item ‘ int number; ivariables declaration private by default float cost; public: void getdata(int a, float b); function declaration using prototype void putdata( ); ‘ Hends with semicolon such as item. This name now be used to declare instances of that class type. bers and two function members. The data ction ate public by declaration. ember variables number We usually give a class some meaningful name, becomes a new type identifier that can ‘> The class item contains two data mem! members are private by default while both the fu to assign values to the m: The function getdata() can be used and cost, and putdata( ) for displaying thei These functions provide the only access to This means that the data can not be accessed by any class item. Note that the functions are detlared, not defined. Actual function defini appear later in the program. ‘The data members are usually declared as private and the member functions as For following figure shows two different notations used by the OOP analysts to represent a class : ° ir values. the data membs function that is not a me! ers from outside the class. ember the * +o itions will public, * getdata() putdata( ) FUNCTIONS getdata( ) putdata() [Representation of a class] Prepared By: - Madhav K. Dave (SSCCS, Bhavnagar) Page 20 of 42 Stoo Shree Swaminarayan College of Computer Science B.Sc. IT- 3 ; ae CC-304, Programming in C++ Or a * Creating objects:~ * Remember that the declaration of item as shown above does not define any objects of \ ‘q,_tem but only specifies what they will contain, * Once a class has been declared, we can create variables of that type by using the class name (like other built-in type variable). For example, item x; // memory for x is created * Creates a variable x and of type item. % In C++, the class variables are known as objects. Therefore, x is called an object of type item. We may also declare more than one object in one statement. For example, item x, y, z 5 // three objects created *% The declaration of an object is similar to that of a variable of any basic type. The necessary memory space is allocated to an object at this stage. Note that class specification, like a structure, provides only a template and does not create any memory space for the objects. Objects can also be created when a class is defined by placing their names immediately after the closing brace, as we do in the case of structures. That is to say, the definition : class item’ Would create the objects x, y and'z of type item. This practice is seldom followed because we would like to declare the objects close to the place where they are used and not at the time of class definition. © Accessing class member: ' ‘> The private data of a class can be accessed only through the member functions of that class. The main( ) can not contain a statements that access number and cost directly. is the format for calling a member functions: the followi For example, the function call statement x.getdata(50,75.5); // It is valid It assigns value to private data member of a class implementing the getdata( ) function. ° + Similarly, the statement : x.putdata( ); L Prepared By: - Madhav K. Dave (SSCCS, Bhavnagar). ' Page 21 of 42 REO P 2¢ Shree Swaminarayan College 9 4 . r-3" ae is CC-304. Programming in C++ : ‘ wes of data members. Remember, 2 member function can be J Would display the val invoked only by using a “> The statement x.number=100; 4 Is also illegal. although x is an object oF number (declared private) can be accessed 0 the object directly. ; Itmay be recalled that objects communicate by sending and receiving is achieves through the member functions. “A variables declared as public can be accesse n object (of the same class). ich number belongs, the f the type item to whic i ter function and not by nly through a mem messages. This .d by the objects directly. © Foreg., class xyz { private: . int x; int ¥5 public: int 25 ys void main() { 11 error, x is private p.z=10; /ok, z is public geteh0; Defining member functions:- ‘Member functions can be defined in two places: (1) Outside the class definition. (2) Inside the class definition. ¢b It is obvious that, irrespective of the place of definition, the function should perform the same task. Therefore, the code for the function body would be identical in both the cases, However, there is subtle difference in the way the function header is defined (1) Outside the class definitior “+ Member functions that are declared insi sid ve 5 . the class. ide a class have to be defined separately outside Pi So repared By: - Madhav K. Dave (SSCS, Bhavnagar) Page 22 of 42 CC-304. Programming in C++ Shree Swaminarayan College of Computer Science?*¥474- a) Sc. I rd [oa] aie % Their definitions are very much like the normal functions. They should have a yeh function header and a function body. Since et does not support the old version of | 7 function definition, the ANSI prototype form must be used for defining the function header. % An important difference between a member function and a normal function jis that a .__ Member function incorporates a membership ‘identity label’ in the header. ‘© This ‘label’ tells the complier which class the function belongs to. The general form of a member function definitions is: return-type class-name ;: function-name(argument declaration) { function body } ‘ The membership label class-name :: tells the compiler that the function function-name belongs to the class class-name. That is, the scope of the function is restricted to the class-name specified in the header line. the symbol :: is called the scope resolution operator. ‘ For instance, consider the member functions getdata() and putdata() as discussed above topics, they may be coded as follows: void item { etdata(int a, float b) number = a; cost = b; } ‘ Since these functions do not retum any value, their retum-type is’ void. function arguments are declared using the ANSI prototype. “ The member functions have some special characteristics that are often used in the program development. these characteristics are: 1. Several different classes can use the same function name. The ‘membership label” will resolve their scope. 2. Member functions can access the private data of the class. A non-member function. can not do so. (However, an exception to this rule is a friend function discussed later). 3. A member function can call another member function directly, without using the dot operator. Prepared By: - Madhav K. Dave (SSCCS, Bhavnagar) Page 23 of 42 : puter Science*+;, aan 24. Shree Swaminarayan % pseIt=3° (oma, inC+ lace the function declaration Je, we could define the item College of Com! T-3" CC-304. Programming (2) Inside the class definition:- Another method of defining a member function is to repl by,the actual function defining inside the class. For examp! class as follows: class item { int number; ‘ float cost; : public: void getdata(int a, float b); ‘//Member function declaration J Inline fanciton void putdata(void) // definition inside the class { cout<

You might also like