CLASSES AND OBJECTS This presentation introduces classes, explain data hiding, abstraction and encapsulation.
CLASSES •Def : A class is a way to bind the data describing an entity and its associated functions together. In C++, class makes a data type that is used to create objects of this type. Classes are needed to represent real-world entities that not only have data type properties (characteristic) but also have associated operations (their behaviors). A class have four associated attributes. 1. DATA MEMBERS are the data type properties that describe the characteristic of a class. 2. MEMBER FUNCTIONS are the set of operations that may be applied to objects of that class. 3. A PROGRAM ACCESS LEVEL that control access to members from within a program. 4. CLASS TAG NAME that serves as a type specifier for the class using which the objects of this class type can be created.
For instance, consider an account having characteristics account no, type and balance. Its associated operations are deposit and withdrawal. class Account { int accountno ; char type ; float balance ; public : float deposit ( float amount ) { balance += amount ; return balance ; } float withdraw ( float amount ) { balance -= amount ; return balance ; } } ; Tag Name Data Members or characteristic Access specifier Member functions or Methods ClassDefinition.DescribeDATA&METHODES
In the software field, a need was felt to create software analogues to real-world objects. The structure of Procedural Programs provide a half way help by binding together the data but still the associated operations were left out. The solution is that, to allow struct to have member functions as well as member data. This is called a class and proves the significance of it. Declaration of Classes involves declaration following four attributes. 1. Data Members are the data-type properties that describe the characteristics of a class. 2. Member functions are the set of operations that may be applied to objects. 3. Program Access Level that control access to members from within the program. Depending upon the Access Level of a class member, access to it is allowed or denied. 4. Class Tag Name serves a type specifier of the class using which objects of this class cab be created.
Referencing Class members. Parrot is an object of class bird. Car is an object of class vehicle. Like that Suresh, Mathew, Jacob are the objects of class sales man. Vishnu, Abhinav, Jebin are objects of Class Student. A class defines the properties of a Salesman or a Student. A class specification does not create any objects, rather it just defines the properties of a class. class STUDENT { int Roll_no , Phy_Mark , Chem_Mark , Bio_Mark , total_mark ; char name[25]; public : void input() { cout << “ Enter Name, Roll No and Marks in 3 Subjects “ ; cin >> name >> Roll_no >> Phy_Mark , Chem_Mark , Bio_Mark ; } void calculate() { total_mark = Phy_Mark + Chem_Mark + Bio_Mark ; } void output() { cout << “Roll No “ << rollno << “ Total Mark : “ << total; } } ;
If you want to manipulate some students, Create instances of class. Instances of class are known as Objects. See the following Program. Void main() { Student a , b , c ; // Call the public member function ‘input()’ in association with Student ‘a’ a.input(); // Call the member function ‘input()’ in association with Student ‘b’ b.input(); a.calculate() ; // call the function for calculate Total Marks of student ‘a’ b.calculate() ; // call the function for calculate Total Marks of student ‘b’ a.output() ; // Display Roll No and Total Mark of Student ‘a’ b.output() ; // Display Roll No and Total Mark of Student ‘b’ }; a, b, c are 3 objects of class student. Or a,b,c are 3 students Referencingobject
Let sobj and cobj are 2 objects of struct S and class C respectively, i.e, S sobj ; C cobj ; To set value 5 for class object cobj, we need to write cobj.setNum(5) ; Whereas for structure object sobj, we can write 2 statements sobj.setNum(5) and sobj.num = 5; With this arises a data security concern because sobj.num = -5 will also get executed, overruling the requirement num should be positive value. class C { int num; public: void setNum(int n) { if (n>0) num = n; else cout << “-ve value not allowed. “; } }; struct S { int num; void setNum(int n) { if (n>0) num = n; else cout << “Negative value not allowed. “; } }; Structures vs Classes in C++ C++ provides structures and classes to create user-defined data types.Structures and Classes are exactly same except default access specifier of their members. In struct all members are public by default while in classes all are private. Consider following.
The Class Methods Definition. Member functions can be defined in two places. (1) Inside the class definition. (2) Outside class definition. class STUDENT { int Roll_no , Phy_Mark , Chem_Mark , Bio_Mark , total_mark ; char name[25]; public : void input() { cout << “ Enter Name, Roll No and Marks in 3 Subjects “ ; cin >> name >> Roll_no >> Phy_Mark , Chem_Mark , Bio_Mark ; } void calculate() { total_mark = Phy_Mark + Chem_Mark + Bio_Mark ; } void output(); } ; void STUDENT :: output() { cout << “Roll No “ << rollno << “ Total Mark : “ << total; } void output() { cout << “Roll No “ << rollno << “ Total Mark : “ << total; } }; Where the class name indicates that the function is a member of the class specified by class. The symbol :: called scope resolution operator, specifies that the scope of the function is restricted to the class- name. The label ‘STUDENT :: ‘ means it is member of STUDENT class.
The Class Methods Definition. Member functions can be defined in two places. Inside the class definition. (2) Outside class definition. (1) Inside the class definition. If you define a function inside a class specification, then the function is treated as inline. Inline property is only a hint to the compiler to insert function definition at the place where it is called. class STUDENT { int Roll_no , Phy_Mark , Chem_Mark , Bio_Mark , total_mark ; char name[25]; public : void input() { cout << “ Enter Name, Roll No and Marks in 3 Subjects “ ; cin >> name >> Roll_no >> Phy_Mark >> Chem_Mark >> Bio_Mark ; } }; main() { STUDENT a; a.input(); } An Inline function insert its definition at the place where it is called. Function definition is written inside the class. So it is treated as Inline.
(2) Outside class definition. class STUDENT { int Roll_no , Phy_Mark , Chem_Mark , Bio_Mark , total_mark ; char name[25]; public : void input() ; }; void STUDENT :: input() { cout << “ Enter Name, Roll No and Marks in 3 Subjects “ ; cin >> name >> Roll_no >> Phy_Mark >> Chem_Mark >> Bio_Mark ; } main() { STUDENT a; a.input(); } Where the class name ‘STUDENT’ indicates that the function is a member of the class specified by class. The symbol :: called scope resolution operator, specifies that the scope of the function is restricted to the class ‘STUDENT’
A class binds together data and its associated functions. Some of them are accessible from outside of that class, and others are not. It will be accomplished by specifying their access. A class provides 3 access labels namely public, private and protected. Public : A member declared as public is made available to all parts of a program, but only using an object of that class. Private : A member declared as private remains hidden from outside world. It can be accessed by the member functions and friend functions of that class. The private members implement the concept of Data-Hiding. Protected : A member declared as protected makes the members hidden but inheritable.
ACCESS SPECIFIERS Access to class members from other part of the program is called SCOPE. Scope of class members is specified by using ACCESS SPECIFIERS. It can be either public, private, or protected. Members of a class can acquire access attributes in one of two ways 1) by default, 2) Explicit use of the access specifiers public, private, and protected. public If a member is public, it can be used by any where in the program. In C++, members of a ‘struct’ or ‘union’ are public by default. private If a member is private, it can only be used by member functions and friends of the class in which it is declared. Members of a class are private by default. protected If a member is protected, its access is the same as for private. In addition, the member can be used by member functions and friends of classes derived from the declared class, but only in objects of the derived type. The protected members can be used within the class. Derived class members and friends of derived class can also access protected members. In other words, ‘protected’ members are protected from unauthorized part in the program.
main() can access ‘a’ and ‘sqr’ members because these are public. class X { public: int a; int sqr( int b) { return b*b; } }; void main(0 { X obj; int c; obj.a = 10; c = obj.sqr(5); } class X { public: int a; int sqr() { return a*a; } }; void main(0 { X obj; int c; obj.a = 10; c = obj.sqr(); }
class X { private: int a; int sqr( ) { return a*a; } public: void assign(int val) { a = val; } int twice() { return a*a; } int newsqr() { int x = sqr(); return x; } }; void main(0 { X obj; int c; obj.a = 10; c = obj.sqr(5); obj.assign(10); c = obj.twice(); OR c = newsqr(); } Private members are not accessibe from outside class. Hence these are prone to errors. newsqr() is a public member. It can be accessible from main(). newsqr() will invoke sqr() and return end result.
The Scope Rules and Classes The visible area of a class member is known as its scope. The scope of a class member depends upon its access specifier (public, private and protected). Let us consider local and global classes. Global Classes A class is said to be global if its definition occurs outside the bodies of all functions in a program. # include <iostream.h> class X { }obj1; OR X obj1; Int main() { X obj2; } void ABC() { X obj2; } Here class X is defined globally. Thus an object of type X can be declared from any where in the program. Obj1 is a global Object, but obj2 and obj3 are Local Objects.
Local Classes. A class is said to be local class if its definition occurs inside a function body.The objects of this class can be declared only within that function. # include <iostream.h> int main() { class X { ……….. }obj1; OR X obj1; } Void abc() { X obj2; } class X is defined within the function main(). So its scope is restricted within main(). We can’t create an instance of this class outside of main(). ERROR ! class X is Local to main(). So we can’t create obj2.
Global Objects. An object is said to be a global object if it is declared outside all function bodies. # include <iostream.h> class X { ……….. }obj1; OR X obj1; int main() { X obj2; } void ABC() { X obj3; } Void PQR() { X obj4; } class X is global class. Because it is declared outside of all functions. obj1 is also global Object. class X is Global. But obj2, obj3 and obj4 are local to main(), ABC() and PQR(). Why ?. These are declared within respective functions.
Local Objects. An object is said to be a local object if it is declared within a function. class X { ……….. }obj1; OR X obj1; int main() { class Y { }; X obj2; // Valid. X is a Global Class. Y obj3; // Valid. Local class Y is declared within this function. } void ABC() { X obj4; // Valid. X is a Global Class. Y obj5; // Invalid. Class Y is local to the function main(). } Void PQR() { X obj5; // Valid. X is a Global Class. Y obj6; // Invalid. Class Y is local to the function main(). } class X is global class. Because it is declared outside of all functions. obj1 is also global Object. class Y is local. We can’t create an instance of this class outside of main().
Scope of Private and Protected Members. The private and protected members of a class have scope only inside the class. It can be accessed only by the member function of that class. # include <iostream.h> class X { private: int a; void out() { cout << “nnThe Value of A is “ << a; } public: int b; void out1() { a = 5; out(); cout << “nnThe Value of B is“ << b; } }; Int main() { X obj; obj.a = 5; obj.b = 10; obj.out(); obj.out1(); } // Invalid. ‘a’ is private member of class X. // Valid. ‘b’ is public member of class Y. // Valid. Out1() is a public member function. // Invalid. out() is a private member function;
Scope of Public members of a Class. The scope of public members depend upon the object being used for referencing them. If the object is a global one then the scope of public members is also global and if the referencing object is a local one then the scope of public members is local. class Y is local. We can’t create an instance of this class in outside of main(). # include <iostream.h> class X { private: int a; void out() { cout << “nnThe Value of A is “ << a; } public: int b; void out1() { a = 5; out(); cout << “nnThe Value of B is“ << b; } }obj1; // obj1 is a global object. Int main() { X obj2; obj1.a = 5; // Invalid. ‘a’ is private member of class X. obj1.b = 10; // Valid. ‘b’ is public member of class Y. obj1.out(); // Invalid. out() is a private member function; obj1.out1(); // Valid. Out1() is a public member function. } void ABC() { X obj3; obj1.b = 10; // Valid. Because obj1 and ‘b’ are public. Obj2.b = 15; // Invalid. Because obj2 is local to main(). obj3.b = 20; // Valid. Because ‘b’ is public member of X }
Element Scope Description. Class Global Local Global Scope Local Scope Global classes are available to all the functions within a program. Objects of them can be created from any function. It is locally available to the function in which the class definition occurs. Objects of this class can be created only within that function. Objects Global Local Global scope Local Scope Global objects can be used anywhere in the program These objects can be used only within the function that declare it. Classes Members Private Protected Public Class scope Base class & Derived classes. Global for Global Objects and Local for Local Objects These members can be accessed by the member functions of that class. These members can be accessed by the member functions of this class .and derived classes If the referencing object is local, the scope of public members is local. If the referencing object is global, the scope of public members is global
Types of Class Functions. The member functions of a class can be categorized into three. i) Accessor Functions. II) Mutator Functions. III) Manager Functions. Accessor Functions. These are member functions that allow us to access the data of an object It can’t change the values of data menbers.Private Data Members are accessible through a public Accessor function. Mutator Functions. These are member functions that allows us to change the values of an object. Manager Functions. These are member functions with specific functions. Constructors and Destructors that deal with initializing and destroying objects are examples of Manager Functions. By making everything public, data become unsafe and vulnerable. It will violate Data-Hiding Feature of OOPs. By providing Accessors and Mutators we make sure that data is edited in desired manner through a mutator. If a user wants to known value of data member, he can get it through an accessor.
class STUDENT { private: int rollno; char name[20], grade; float marks; public: void getdata() { cout << “nEnter Name, Roll No and Marks “; cin >> name >> rollno >> marks; } void putdata() { cout << “nStudent “ << name << “ got “ << grade << “ Grade.”; } int get_rollno() { return roll; } float get_marks() { return marks; } void calc_grade() { if (marks >= 75) grade = ‘A’; else if(marks >=60) grade = ‘B’; else if (marks >= 50) grade = ‘C’; else grade = ‘D’; } };
Nested Classes A class declared within another class is called Nested Class. The outer class is known as Enclosing Class and the inner class is known as Nested Class. The objects of nested class can be declared only within its enclosing class. class A { private : int a, ……………………….. class B { private : int b; }; B bobj; }; Inner Class Or Nested Class Outer Class Or Enclosed Class Object of Inner Class
# include <iostream.h> # include <conio.h> class A { private: class B { public: void out() { cout << "nnI am B out."; } }; public: void out() { cout << "nnI am A out"; } }; void main() { A a; // Object of Outer class A. A :: B b; // It is an object of Inner Class B a.out(); // Calling out() of Outer class A. b.out(); // Calling out() of Inner class B. getch(); }
main() { outer ab; inner bc; outer :: inner cd; ab.second(); bc.prn(); cd.prn(); getch(); } # include <iostream.h> # include <conio.h> class outer { int a; class inner { int b; public: int c; void prn(void) { cout << “nInner Prn () " << b << ", " << c; } inner() { b=5; c = 10; } }; inner ob1; public: inner ob2; void second() { cout << "Outer Second" << ob2.c << "A="<< a; } outer() { a = 25; } }; The class definition of inner appears in the private section of outer. It means that the inner class is privately available to Outer. If it appears in public section, then the inner class become available to All.
Member Access Control of Nested Classes. The member functions of a nested class have no special access to the members of an enclosing class. They obey usual access rules. And the same is true for an enclosing class for the access of nested class members. That is nested class can access public members of its enclosing class using an object only. An enclosing class can access public members of nested class through an object. class Outer { int a; class Inner { int b; public : int c; void prn() { cout << b*c; cout << a; } }; Inner ob1; public: Inner ob2; void second() { cout << ob2.c * ob1.c; cout << b; } }; By default, all members of a class are Private. ERROR ! ‘a’ is private to Outer. So Outer :: a is not accessible from Inner Class. ERROR ! ‘b’ is private to Inner. So Inner :: b is not accessible from Outer Class.
Abstraction refers to the act of representing essential features without including the background details. Data Hiding refers to the act that the relevant information is exposed to the user and rest of the in formations remain hidden from the user. Encapsulation refers to wrapping up data and functions into a single unit. The class bind the data and associated functions into a single-type which is encapsulation. The class groups its members into 3 sections private, protected and public, where private and protected members remain hidden from outside world and there by support data-hiding. The public members providing the essential and relevant informations to the outside world. Thus only the essential features are represented to outside world, without including the background details which is nothing but abstraction.
Working of Normal Function. An executable code consists of a set machine language instructions. When this program is executed, Operating System loads these instructions into computer’s memory.. Thus each instruction has a particular memory address. These instructions are executed step by step. When a function being called, Operating System do 1. save the address of instruction immediately following the function call.( Here 1018 ) 2. Loads the function being called into the memory (Here 2022 ), copies argument values. ( Here c = 11 ) 3. Jump to the memory location of the called function. ( Here 2022 ) 4. execute the code. ( Calculate 11 * 11 = 121 ) 5. stores the returning value. ( Here d become 121 ) 6.Jump back to early saved address that was the address of instruction immediately following the function call. ( Here 1018 cout << d; } Memory-loaded program ……… ……………….. 1010 Int a = 4, b = 7; 1012 Int c = a + b, d; 1015 d = square( c ) ; 1018 cout << d; ………………………. 2022 Int square ( int i ) 2024 { return i*I; }
Inline Functions. Those functions, the compiler replace the function call statement with the function code itself are known as Inline Functions. Original Program void main() { …… square(3); Code Replace here … square(5); Code Replace here ……….. square(7); Code Replace here } void square(int a) { cout << a*a; } Inline Functions. Compiled Program void main() { …… { cout << 3*3; } …………. { cout << 3*3; } ……….. { cout << 3*3; } } AnInlinefunctioninsert itsdefinitionattheplace whereitiscalled.
A function can be declared inline by placing the keyword inline before it. Inline Function definition should be placed above all the functions that call It. The member functions defined within the class definition are inlined by default. Inline Functions run a little faster than the normal function as function-calling- overheads are saved, however, there is a memory penalty. If 10 times an Inline function is called, there will be 10 copies of the function inserted into the code. Inline functions are best for small functions that are called often. The compiler may even ignore your attempt to inline a function, if that function is very large and being called over and over. Inline does not work for following situations. 1. For functions that return values and having a loop / switch / goto statement. 2. For functions not return values, if a return statement exists. 3. If functions contains static variables. 4. If the function is recursive ( a function that call itself.).
# include <iostream.h> # include <conuio.h> Inline int max(int a, int b) { if (a>b) return a; else return b; } Inline int sum (int n) { for ( int s=0; n>0; n--) s += n; return s; } Inline int add (int n) { for ( int s=0; n>0; n--) s += n; } main() { cout << “Max Value = “ << max(10,5); cout << “Sum of Nos 1..10 = “ << sum(10); cout << “Sum of Nos 1..10 = “ << add(10); } Valid. A function can be declared by placing the keyword ‘inline’. Invalid !. A function having loop/switch/goto are can’t be inline. Invalid !. A function not returning a value. Some examples of Inline functions.
Constant Member Functions. A member function that does not have alter any data are known as constant member function. If a member function of a class does not alter any data in the class, then, this function may be declared as a constant member function using the keyword ‘const’. # include <iostream.h> # include <conio.h> class X { int a; public : void assign ( int val) const { a = val; } void setval ( int val ) { a = val; } void out() const { cout << “The Value of A = “ << a; } }; Error !. A const member function does not alter Data. Valid. setval () is not a const member function. So it can alter Data.
Nesting of Member Functions. When a member function is called by another member function, it is called nesting of member function. # include <iostream.h> class student { int roll_no, m1,m2,m3, tot; char name [20]; void cal_total() { tot = m1 + m2 + m3; } public: void input() { cout << “nEnter Name, Roll No & 3 Marks “; cin >> name >> roll >> m1 >> m2 >> m3; cal_total(); } Void out() { cout << “nnTotal Marks = “ << tot; } }; int main() { student a; a.input(); a.out(); } Private cal_tot() can’t be called from main(). The function ‘cal_tot() call from ‘input()’.
The Scope Resolution Operator :: Scope Resolution operator is used to distinguish between class members and other names. # include <iostream.h> Int a = 10; class X { int a; public: void X :: out() { cout << “Class member A = “ << a; // or X :: a cout << “Value of Global variable A is “ << :: a; } void X :: assign ( int n ) { X :: a = n; } }; main() { X obj; obj.assign(20); obj.out(); } In this class the full name of variable ‘a’ is ‘X :: a’. The full name of a class member is also called ‘Qualified Name”. The qualified name of out() is X :: out(); Use :: for global variables if they are hidden by a local variable. Qualified Name of member function X :: assign() Qualified Name of member function out() is X :: out() Insidethisclassglobal variable‘a’ishiddenname.
Using Objects. When you define a class, it does not create objects of that class, rather it only specifies what type of information the objects of this class will be containing. Once a class has been defined its instances (objects) can be created like any other variable, using the class name. # include <iostream.h> class length { int cm,m; public: void input(); void out(); } void length :: out() { cout << “nGiven Length is “ << m << “ mtr and “ << cm << “ cms”; } void length :: input() { cout << “nnEnter the length in Meter & Cm. “; cin >> m >> cm; } Int main() { length a; a.input(); a.out(); } Creating instance of class length.
We have already know that the memory space for objects is allocated when they are declared and not when the class is defined. Member functions are created and placed in the memory only once when the class is defined. The memory space is allocated for data members only when the objects are created. No separated space is allocated for member functions. Since all the objects belonging to a class use same functions, there is no separate space for member functions. Thus member functions are created and stored when the class is defined and this memory space can be shared by all instance of that class. Separated memory space is allocated for the data members. Because the data members holds different values for different objects.
# include <iostream.h> class length { Int feet, inch; public: void input() { cout << “Enter Feet and Inches “; cin >> feet >> inch; } void out() { cout << “Feet = “ << feet; cout << “Inch =“ << inch; } }obj1, obj2, obj3; Memory for obj1 Feet = 7, inch = 3 Memory for obj2 Feet = 7, inch = 3 Memory for obj3 Feet = 7, inch = 3 ………………………………………… Memory Space for Member Functions ………………………………………… void input () { } void input () { } Separate Memory Space for Data-Members of each Objects. No separate Memory Space for Member Functions. Only one copy of member functions are shared by all objects.
# include <iostream.h> class length { Int feet, inch; public: void input() { cout << “Enter Feet and Inches “; cin >> feet >> inch; } void out() { cout << “Feet = “ << feet; cout << “Inch =“ << inch; } }obj1; void main() { length obj2, obj3; cout << “nSize of obj1 is “ << sizeof(obj1); cout << “nSize of obj2 is “ << sizeof(obj2); cout << “nSize of obj3 is “ << sizeof(obj3); cout << “Size of Class Length “ << sizeof (length); } Output: Size of obj1 is : 4 Size of obj2 is : 4 Size of obj2 is : 4 Size of Class Length : 4 The memory space is allocated for data members of each objects. No separated space is allocated for member functions. 2 byte feet + 2 byte inch = 4 byte.
Array of Objects. An array is a collection of elements of same type, that are referenced by a common name. An Array having class type elements is known as Array of Objects. Element of the array can be referenced by saying its position from starting element. The No indicating element's position is called Array Index. Array index start from 0 and are uptill size – 1. Elements are stored in consecutive memory cell. class student { int Roll; float per_marks; char name[20]; } a[10]; 99 100 126 152 178 204 230 256 282 308 334 335 …. A[0] A[1] A[2] A[3] A[4] A[5] A[6] A[7] A[8] A[9] …. Consecutive Memory Cells and its Address. The size of a student is 26 (Roll 2 + per_marks 4 + Name 20 = 26). Here address being start from 100 and will be incremented by 26. 2 bytes Roll No 4 bytes per_marks 20 bytes Name
# include <iostream.h> class Item { Int item_no; float price; public: void getdata(int n, float p) { item_no = n; price = p; } void putdata() { cout << “n” << item_no << “t” << price; } }; int main() { Item a[10]; int i, itn; float p; for(i=0; i<10; i++) { cout << “nEnter Item No & Price “; cin >> itn >> p; a[i].getdata(itn, p); } for(i=0; i<10; i++) a[i].putdata(); } Declare an array having 10 elements of type class item. a[0] - First element in the Array. a[1] - Second element in the Array. a[2] - Third element in the Array. …… a[9] – 10th element in the Array. A[0].getdata (ino, p); Call the function getdata() in association with a[0]th element, and assign itn in item_no and p in price. Array Index Data member 0th element Item_no = 100 price = 25.75 1st element item_no = 101 price = 30.50 2nd element item_no = 102 price = 15.00 ‘i’ start from 0 and increment by 1. Read item No and price from the user and assign these values in respective data members of a[0], a[1], a[2] … Print data members of successive Array elements a[0], a[1], a[2] … a[9] using a for loop through the accessor function putdata().
Objects as Function Argument. The values passed to a function are called Argument or Parameter. The values given in function calling statement is Actual Argument and the Objects received them at function definition are called Formal Arguments. Like any other data type, an object may also be passed as argument. The object can also be passed both ways By Value and By Reference. Function Call By Value. When an object is passed by value, the function creates its own copy of the object and works with its copy. Therefore any changes made in the object inside the function dol not affect actual object. Int main() void swap (int x, int y) { { int a = 10, b = 20; int z = x; swap (a, b); x = y; y = z; } } Function Call By Reference. When the object is passed by reference, its memory address is passed to the function so that the called function works directly on the orginal object used in the function call. Int main() void swap (int &x, int &y) { { int a = 10, b = 20; int z = x; swap (a, b); x = y; y = z; } }
# include <iostream.h> # include <conio.h> class length { public: int m, cm; void input(); void out(); }; void length :: input() { cout << "nnEnter Meter & Cm"; cin >> m >> cm; } void length :: out() { cout << "nn " << m << " Meters and “ << cm << " Cms."; } Call By Value. A function add(length l1, length l2) will add 2 length. length add(length l1, length l2) { length l3; l3.m = l1.m + l2.m; l3.cm = l1.cm + l2.cm; if(l3.cm>=100) { l3.m++; l3.cm-=100; } return l3; } int main() { length a, b, c; a.input(); b.input(); a.out(); b.out(); c = add(a,b); c.out(); getch(); } m and cm are public data members. So these can be accessible.
# include <iostream.h> # include <conio.h> class length { int m, cm; public: void input(); void out(); friend length add (length l1, length l2); }; void length :: input() { cout << "nnEnter Meter & Cm"; cin >> m >> cm; } void length :: out() { cout << "nn " << m << " Meters and “ << cm << " Cms."; } Friend Function. It is possible to grand a nonmember function access to the private members of a class. A friend function has access to all the members of a the class for which it is a friend. By declare a function proceeding with the keyword ‘friend’ within the class, that function become ‘friend’. Here add(length l1, length l2) is a friend of class length. length add(length l1, length l2) { length l3; l3.m = l1.m + l2.m; l3.cm = l1.cm + l2.cm; if(l3.cm>=100) { l3.m++; l3.cm-=100; } return l3; } int main() { length a, b, c; a.input(); b.input(); a.out(); b.out(); c = add(a,b); c.out(); getch(); } By declaring the function add() proceeding with the keyword ‘friend’, it become ‘friend’ of class length. So add() can access m and cm.
# include <iostream.h> # include <conio.h> # include <string.h> // to use strcpy() class time { int h,m,s; char suf[8]; public: void input(); void out(); friend void change_24hrs(time &t); }; void time :: input() { cout << "nnEnter Hrs, Min and Sec”; cin >> h >> m >> s; cout << “ Suffix AM/PM ?."; cin >> suf; } void time :: out() { cout<<"nn"<<h<<":"<<m<<":"<<s << suf; } void change_24hrs(time &t) { if ( strcmp(t.suf,"PM") == 0 ) { t.h+=12; strcpy(t.suf, " 24 Hrs"); } } int main() { time t; t.input(); t.out(); change_24hrs(t); t.out(); getch(); } Function Call By Reference. When the object is passed by reference, its memory address is passed to the function so that the called function works directly on the orginal object used in the function call. If you remove ‘&’ then it become Call by value. In that case the output would be incorrect. Write this program with and without ‘&’ and see the Difference.
STATIC CLASS MEMBERS. There are two types of Static Members. (i) Static Data Members. (ii) Static Functions. Static Data members of a Class. Only one copy of data that are shared by all the objects of that class are called Static Data Members. The static data members are usually maintained to store values common to the entire class. Such data will provide access control to some shared resources used by all objects of a class. Since they are associated with the class itself, rather than with any objects they are also known as class variables. You can declare a Static variable preceded with the keyword ‘static’. class X { static int a; ….. }; Static Data Members is different from ordinary Data Members in various respect. 1. There is only one copy of this data maintained for the entire class which is shared by all the objects of that class. 2. It is visible only within the class however its life time is the entire program. Tthe time for which a value remains in the memory is called ‘life time.’ Two things are needed for making a data member static. i) Declare it within the class. ii) Define it outside the class definition.
# include <iostream.h> # include <conio.h> class student { int Roll_no; char name[20], std[7]; static char school[30]; public: void input(); void output(); }; void student :: output() { cout << "nnName : " << name; cout << "nnRoll No : " << Roll_no; cout << "nnSchool : " << school; } void student :: input() { cout << "nnPls enter Name & Roll No "; cin >> name >> Roll_no; } char student :: school[30] = "VidhyadhiRaja"; int main() { student a,b; a.input(); b.input(); a.output(); b.output(); getch(); } Output. Pls enter Name & Roll No : Raman 100 Pls enter Name & Roll No : Soman 101 Name : Roman Roll No : 100 School : VidhyadhiRaja Name : Soman Roll No : 101 School : VidhyadhiRaja Declared it within the class precede with ‘static’ and also Defined/initialize it outside the class definition Sharing Same Data along several Objects. Static Data are common to all objects.
Static Member Function. A member Function that access only the static members of a class may be declared as static. By putting the keyword ‘static’ before the function declaration, member function becomes ‘static’. A Static Member Function is different from other member functions in various respects. A Static Member function can access only static members of the class. A static Member function is invoked by using the class name instead of its objects. class student { ….. static char school[30]; static void assignschool() { Strcpy(school, “”); } }; main() { student :: assignschool(); }
# include <iostream.h> # include <conio.h> # include <string.h> class student { int Roll_no; char name[20], std[7]; static char school[30]; public: static void assign_school(char nam[]); void input(); void output(); }; void student :: input() { cout << "nnPls enter Name & Roll No "; cin >> name >> Roll_no; } void student :: assign_school(char nam[]) { strcpy(school, nam); } void student :: output() { cout << "nnName : " << name; cout << “nnRoll No ::“ << Roll_no; cout << "nnSchool : " << school; } char student :: school[30]; int main() { student a,b; student :: assign_school ("V R. V. P"); a.input(); b.input(); a.output(); b.output(); getch(); } Putting the keyword ‘static’ before the function declaration, it becomes ‘static’. Static Member function can access only static members of the class. static Member function is invoked by using the class name instead of its objects.
A class definition does not create Objects. Objects are to be created separately. The Member functions are commonly created and stored in the memory for all Objects. The objects are created separately to store their data members. The Objects can be passed to as well as returned from function. The static data members are global variables for its class type objects. These are commonly shared by all the objects of that class type. The static member functions are the functions that can access only the static data. The ordinary member functions can access both static as well as ordinary members of a class.
CLASSES AND OBJECTS IN C++ +2 COMPUTER SCIENCE

CLASSES AND OBJECTS IN C++ +2 COMPUTER SCIENCE

  • 1.
    CLASSES AND OBJECTS Thispresentation introduces classes, explain data hiding, abstraction and encapsulation.
  • 2.
    CLASSES •Def : Aclass is a way to bind the data describing an entity and its associated functions together. In C++, class makes a data type that is used to create objects of this type. Classes are needed to represent real-world entities that not only have data type properties (characteristic) but also have associated operations (their behaviors). A class have four associated attributes. 1. DATA MEMBERS are the data type properties that describe the characteristic of a class. 2. MEMBER FUNCTIONS are the set of operations that may be applied to objects of that class. 3. A PROGRAM ACCESS LEVEL that control access to members from within a program. 4. CLASS TAG NAME that serves as a type specifier for the class using which the objects of this class type can be created.
  • 3.
    For instance, consideran account having characteristics account no, type and balance. Its associated operations are deposit and withdrawal. class Account { int accountno ; char type ; float balance ; public : float deposit ( float amount ) { balance += amount ; return balance ; } float withdraw ( float amount ) { balance -= amount ; return balance ; } } ; Tag Name Data Members or characteristic Access specifier Member functions or Methods ClassDefinition.DescribeDATA&METHODES
  • 4.
    In the softwarefield, a need was felt to create software analogues to real-world objects. The structure of Procedural Programs provide a half way help by binding together the data but still the associated operations were left out. The solution is that, to allow struct to have member functions as well as member data. This is called a class and proves the significance of it. Declaration of Classes involves declaration following four attributes. 1. Data Members are the data-type properties that describe the characteristics of a class. 2. Member functions are the set of operations that may be applied to objects. 3. Program Access Level that control access to members from within the program. Depending upon the Access Level of a class member, access to it is allowed or denied. 4. Class Tag Name serves a type specifier of the class using which objects of this class cab be created.
  • 5.
    Referencing Class members. Parrotis an object of class bird. Car is an object of class vehicle. Like that Suresh, Mathew, Jacob are the objects of class sales man. Vishnu, Abhinav, Jebin are objects of Class Student. A class defines the properties of a Salesman or a Student. A class specification does not create any objects, rather it just defines the properties of a class. class STUDENT { int Roll_no , Phy_Mark , Chem_Mark , Bio_Mark , total_mark ; char name[25]; public : void input() { cout << “ Enter Name, Roll No and Marks in 3 Subjects “ ; cin >> name >> Roll_no >> Phy_Mark , Chem_Mark , Bio_Mark ; } void calculate() { total_mark = Phy_Mark + Chem_Mark + Bio_Mark ; } void output() { cout << “Roll No “ << rollno << “ Total Mark : “ << total; } } ;
  • 6.
    If you wantto manipulate some students, Create instances of class. Instances of class are known as Objects. See the following Program. Void main() { Student a , b , c ; // Call the public member function ‘input()’ in association with Student ‘a’ a.input(); // Call the member function ‘input()’ in association with Student ‘b’ b.input(); a.calculate() ; // call the function for calculate Total Marks of student ‘a’ b.calculate() ; // call the function for calculate Total Marks of student ‘b’ a.output() ; // Display Roll No and Total Mark of Student ‘a’ b.output() ; // Display Roll No and Total Mark of Student ‘b’ }; a, b, c are 3 objects of class student. Or a,b,c are 3 students Referencingobject
  • 7.
    Let sobj andcobj are 2 objects of struct S and class C respectively, i.e, S sobj ; C cobj ; To set value 5 for class object cobj, we need to write cobj.setNum(5) ; Whereas for structure object sobj, we can write 2 statements sobj.setNum(5) and sobj.num = 5; With this arises a data security concern because sobj.num = -5 will also get executed, overruling the requirement num should be positive value. class C { int num; public: void setNum(int n) { if (n>0) num = n; else cout << “-ve value not allowed. “; } }; struct S { int num; void setNum(int n) { if (n>0) num = n; else cout << “Negative value not allowed. “; } }; Structures vs Classes in C++ C++ provides structures and classes to create user-defined data types.Structures and Classes are exactly same except default access specifier of their members. In struct all members are public by default while in classes all are private. Consider following.
  • 8.
    The Class MethodsDefinition. Member functions can be defined in two places. (1) Inside the class definition. (2) Outside class definition. class STUDENT { int Roll_no , Phy_Mark , Chem_Mark , Bio_Mark , total_mark ; char name[25]; public : void input() { cout << “ Enter Name, Roll No and Marks in 3 Subjects “ ; cin >> name >> Roll_no >> Phy_Mark , Chem_Mark , Bio_Mark ; } void calculate() { total_mark = Phy_Mark + Chem_Mark + Bio_Mark ; } void output(); } ; void STUDENT :: output() { cout << “Roll No “ << rollno << “ Total Mark : “ << total; } void output() { cout << “Roll No “ << rollno << “ Total Mark : “ << total; } }; Where the class name indicates that the function is a member of the class specified by class. The symbol :: called scope resolution operator, specifies that the scope of the function is restricted to the class- name. The label ‘STUDENT :: ‘ means it is member of STUDENT class.
  • 9.
    The Class MethodsDefinition. Member functions can be defined in two places. Inside the class definition. (2) Outside class definition. (1) Inside the class definition. If you define a function inside a class specification, then the function is treated as inline. Inline property is only a hint to the compiler to insert function definition at the place where it is called. class STUDENT { int Roll_no , Phy_Mark , Chem_Mark , Bio_Mark , total_mark ; char name[25]; public : void input() { cout << “ Enter Name, Roll No and Marks in 3 Subjects “ ; cin >> name >> Roll_no >> Phy_Mark >> Chem_Mark >> Bio_Mark ; } }; main() { STUDENT a; a.input(); } An Inline function insert its definition at the place where it is called. Function definition is written inside the class. So it is treated as Inline.
  • 10.
    (2) Outside classdefinition. class STUDENT { int Roll_no , Phy_Mark , Chem_Mark , Bio_Mark , total_mark ; char name[25]; public : void input() ; }; void STUDENT :: input() { cout << “ Enter Name, Roll No and Marks in 3 Subjects “ ; cin >> name >> Roll_no >> Phy_Mark >> Chem_Mark >> Bio_Mark ; } main() { STUDENT a; a.input(); } Where the class name ‘STUDENT’ indicates that the function is a member of the class specified by class. The symbol :: called scope resolution operator, specifies that the scope of the function is restricted to the class ‘STUDENT’
  • 11.
    A class bindstogether data and its associated functions. Some of them are accessible from outside of that class, and others are not. It will be accomplished by specifying their access. A class provides 3 access labels namely public, private and protected. Public : A member declared as public is made available to all parts of a program, but only using an object of that class. Private : A member declared as private remains hidden from outside world. It can be accessed by the member functions and friend functions of that class. The private members implement the concept of Data-Hiding. Protected : A member declared as protected makes the members hidden but inheritable.
  • 12.
    ACCESS SPECIFIERS Access toclass members from other part of the program is called SCOPE. Scope of class members is specified by using ACCESS SPECIFIERS. It can be either public, private, or protected. Members of a class can acquire access attributes in one of two ways 1) by default, 2) Explicit use of the access specifiers public, private, and protected. public If a member is public, it can be used by any where in the program. In C++, members of a ‘struct’ or ‘union’ are public by default. private If a member is private, it can only be used by member functions and friends of the class in which it is declared. Members of a class are private by default. protected If a member is protected, its access is the same as for private. In addition, the member can be used by member functions and friends of classes derived from the declared class, but only in objects of the derived type. The protected members can be used within the class. Derived class members and friends of derived class can also access protected members. In other words, ‘protected’ members are protected from unauthorized part in the program.
  • 13.
    main() can access ‘a’and ‘sqr’ members because these are public. class X { public: int a; int sqr( int b) { return b*b; } }; void main(0 { X obj; int c; obj.a = 10; c = obj.sqr(5); } class X { public: int a; int sqr() { return a*a; } }; void main(0 { X obj; int c; obj.a = 10; c = obj.sqr(); }
  • 14.
    class X { private: int a; intsqr( ) { return a*a; } public: void assign(int val) { a = val; } int twice() { return a*a; } int newsqr() { int x = sqr(); return x; } }; void main(0 { X obj; int c; obj.a = 10; c = obj.sqr(5); obj.assign(10); c = obj.twice(); OR c = newsqr(); } Private members are not accessibe from outside class. Hence these are prone to errors. newsqr() is a public member. It can be accessible from main(). newsqr() will invoke sqr() and return end result.
  • 15.
    The Scope Rulesand Classes The visible area of a class member is known as its scope. The scope of a class member depends upon its access specifier (public, private and protected). Let us consider local and global classes. Global Classes A class is said to be global if its definition occurs outside the bodies of all functions in a program. # include <iostream.h> class X { }obj1; OR X obj1; Int main() { X obj2; } void ABC() { X obj2; } Here class X is defined globally. Thus an object of type X can be declared from any where in the program. Obj1 is a global Object, but obj2 and obj3 are Local Objects.
  • 16.
    Local Classes. A classis said to be local class if its definition occurs inside a function body.The objects of this class can be declared only within that function. # include <iostream.h> int main() { class X { ……….. }obj1; OR X obj1; } Void abc() { X obj2; } class X is defined within the function main(). So its scope is restricted within main(). We can’t create an instance of this class outside of main(). ERROR ! class X is Local to main(). So we can’t create obj2.
  • 17.
    Global Objects. An objectis said to be a global object if it is declared outside all function bodies. # include <iostream.h> class X { ……….. }obj1; OR X obj1; int main() { X obj2; } void ABC() { X obj3; } Void PQR() { X obj4; } class X is global class. Because it is declared outside of all functions. obj1 is also global Object. class X is Global. But obj2, obj3 and obj4 are local to main(), ABC() and PQR(). Why ?. These are declared within respective functions.
  • 18.
    Local Objects. Anobject is said to be a local object if it is declared within a function. class X { ……….. }obj1; OR X obj1; int main() { class Y { }; X obj2; // Valid. X is a Global Class. Y obj3; // Valid. Local class Y is declared within this function. } void ABC() { X obj4; // Valid. X is a Global Class. Y obj5; // Invalid. Class Y is local to the function main(). } Void PQR() { X obj5; // Valid. X is a Global Class. Y obj6; // Invalid. Class Y is local to the function main(). } class X is global class. Because it is declared outside of all functions. obj1 is also global Object. class Y is local. We can’t create an instance of this class outside of main().
  • 19.
    Scope of Privateand Protected Members. The private and protected members of a class have scope only inside the class. It can be accessed only by the member function of that class. # include <iostream.h> class X { private: int a; void out() { cout << “nnThe Value of A is “ << a; } public: int b; void out1() { a = 5; out(); cout << “nnThe Value of B is“ << b; } }; Int main() { X obj; obj.a = 5; obj.b = 10; obj.out(); obj.out1(); } // Invalid. ‘a’ is private member of class X. // Valid. ‘b’ is public member of class Y. // Valid. Out1() is a public member function. // Invalid. out() is a private member function;
  • 20.
    Scope of Publicmembers of a Class. The scope of public members depend upon the object being used for referencing them. If the object is a global one then the scope of public members is also global and if the referencing object is a local one then the scope of public members is local. class Y is local. We can’t create an instance of this class in outside of main(). # include <iostream.h> class X { private: int a; void out() { cout << “nnThe Value of A is “ << a; } public: int b; void out1() { a = 5; out(); cout << “nnThe Value of B is“ << b; } }obj1; // obj1 is a global object. Int main() { X obj2; obj1.a = 5; // Invalid. ‘a’ is private member of class X. obj1.b = 10; // Valid. ‘b’ is public member of class Y. obj1.out(); // Invalid. out() is a private member function; obj1.out1(); // Valid. Out1() is a public member function. } void ABC() { X obj3; obj1.b = 10; // Valid. Because obj1 and ‘b’ are public. Obj2.b = 15; // Invalid. Because obj2 is local to main(). obj3.b = 20; // Valid. Because ‘b’ is public member of X }
  • 21.
    Element Scope Description. Class Global Local GlobalScope Local Scope Global classes are available to all the functions within a program. Objects of them can be created from any function. It is locally available to the function in which the class definition occurs. Objects of this class can be created only within that function. Objects Global Local Global scope Local Scope Global objects can be used anywhere in the program These objects can be used only within the function that declare it. Classes Members Private Protected Public Class scope Base class & Derived classes. Global for Global Objects and Local for Local Objects These members can be accessed by the member functions of that class. These members can be accessed by the member functions of this class .and derived classes If the referencing object is local, the scope of public members is local. If the referencing object is global, the scope of public members is global
  • 22.
    Types of ClassFunctions. The member functions of a class can be categorized into three. i) Accessor Functions. II) Mutator Functions. III) Manager Functions. Accessor Functions. These are member functions that allow us to access the data of an object It can’t change the values of data menbers.Private Data Members are accessible through a public Accessor function. Mutator Functions. These are member functions that allows us to change the values of an object. Manager Functions. These are member functions with specific functions. Constructors and Destructors that deal with initializing and destroying objects are examples of Manager Functions. By making everything public, data become unsafe and vulnerable. It will violate Data-Hiding Feature of OOPs. By providing Accessors and Mutators we make sure that data is edited in desired manner through a mutator. If a user wants to known value of data member, he can get it through an accessor.
  • 23.
    class STUDENT { private: int rollno; charname[20], grade; float marks; public: void getdata() { cout << “nEnter Name, Roll No and Marks “; cin >> name >> rollno >> marks; } void putdata() { cout << “nStudent “ << name << “ got “ << grade << “ Grade.”; } int get_rollno() { return roll; } float get_marks() { return marks; } void calc_grade() { if (marks >= 75) grade = ‘A’; else if(marks >=60) grade = ‘B’; else if (marks >= 50) grade = ‘C’; else grade = ‘D’; } };
  • 24.
    Nested Classes A classdeclared within another class is called Nested Class. The outer class is known as Enclosing Class and the inner class is known as Nested Class. The objects of nested class can be declared only within its enclosing class. class A { private : int a, ……………………….. class B { private : int b; }; B bobj; }; Inner Class Or Nested Class Outer Class Or Enclosed Class Object of Inner Class
  • 25.
    # include <iostream.h> #include <conio.h> class A { private: class B { public: void out() { cout << "nnI am B out."; } }; public: void out() { cout << "nnI am A out"; } }; void main() { A a; // Object of Outer class A. A :: B b; // It is an object of Inner Class B a.out(); // Calling out() of Outer class A. b.out(); // Calling out() of Inner class B. getch(); }
  • 26.
    main() { outer ab; inner bc; outer:: inner cd; ab.second(); bc.prn(); cd.prn(); getch(); } # include <iostream.h> # include <conio.h> class outer { int a; class inner { int b; public: int c; void prn(void) { cout << “nInner Prn () " << b << ", " << c; } inner() { b=5; c = 10; } }; inner ob1; public: inner ob2; void second() { cout << "Outer Second" << ob2.c << "A="<< a; } outer() { a = 25; } }; The class definition of inner appears in the private section of outer. It means that the inner class is privately available to Outer. If it appears in public section, then the inner class become available to All.
  • 27.
    Member Access Controlof Nested Classes. The member functions of a nested class have no special access to the members of an enclosing class. They obey usual access rules. And the same is true for an enclosing class for the access of nested class members. That is nested class can access public members of its enclosing class using an object only. An enclosing class can access public members of nested class through an object. class Outer { int a; class Inner { int b; public : int c; void prn() { cout << b*c; cout << a; } }; Inner ob1; public: Inner ob2; void second() { cout << ob2.c * ob1.c; cout << b; } }; By default, all members of a class are Private. ERROR ! ‘a’ is private to Outer. So Outer :: a is not accessible from Inner Class. ERROR ! ‘b’ is private to Inner. So Inner :: b is not accessible from Outer Class.
  • 28.
    Abstraction refers tothe act of representing essential features without including the background details. Data Hiding refers to the act that the relevant information is exposed to the user and rest of the in formations remain hidden from the user. Encapsulation refers to wrapping up data and functions into a single unit. The class bind the data and associated functions into a single-type which is encapsulation. The class groups its members into 3 sections private, protected and public, where private and protected members remain hidden from outside world and there by support data-hiding. The public members providing the essential and relevant informations to the outside world. Thus only the essential features are represented to outside world, without including the background details which is nothing but abstraction.
  • 29.
    Working of NormalFunction. An executable code consists of a set machine language instructions. When this program is executed, Operating System loads these instructions into computer’s memory.. Thus each instruction has a particular memory address. These instructions are executed step by step. When a function being called, Operating System do 1. save the address of instruction immediately following the function call.( Here 1018 ) 2. Loads the function being called into the memory (Here 2022 ), copies argument values. ( Here c = 11 ) 3. Jump to the memory location of the called function. ( Here 2022 ) 4. execute the code. ( Calculate 11 * 11 = 121 ) 5. stores the returning value. ( Here d become 121 ) 6.Jump back to early saved address that was the address of instruction immediately following the function call. ( Here 1018 cout << d; } Memory-loaded program ……… ……………….. 1010 Int a = 4, b = 7; 1012 Int c = a + b, d; 1015 d = square( c ) ; 1018 cout << d; ………………………. 2022 Int square ( int i ) 2024 { return i*I; }
  • 30.
    Inline Functions. Those functions,the compiler replace the function call statement with the function code itself are known as Inline Functions. Original Program void main() { …… square(3); Code Replace here … square(5); Code Replace here ……….. square(7); Code Replace here } void square(int a) { cout << a*a; } Inline Functions. Compiled Program void main() { …… { cout << 3*3; } …………. { cout << 3*3; } ……….. { cout << 3*3; } } AnInlinefunctioninsert itsdefinitionattheplace whereitiscalled.
  • 31.
    A function canbe declared inline by placing the keyword inline before it. Inline Function definition should be placed above all the functions that call It. The member functions defined within the class definition are inlined by default. Inline Functions run a little faster than the normal function as function-calling- overheads are saved, however, there is a memory penalty. If 10 times an Inline function is called, there will be 10 copies of the function inserted into the code. Inline functions are best for small functions that are called often. The compiler may even ignore your attempt to inline a function, if that function is very large and being called over and over. Inline does not work for following situations. 1. For functions that return values and having a loop / switch / goto statement. 2. For functions not return values, if a return statement exists. 3. If functions contains static variables. 4. If the function is recursive ( a function that call itself.).
  • 32.
    # include <iostream.h> #include <conuio.h> Inline int max(int a, int b) { if (a>b) return a; else return b; } Inline int sum (int n) { for ( int s=0; n>0; n--) s += n; return s; } Inline int add (int n) { for ( int s=0; n>0; n--) s += n; } main() { cout << “Max Value = “ << max(10,5); cout << “Sum of Nos 1..10 = “ << sum(10); cout << “Sum of Nos 1..10 = “ << add(10); } Valid. A function can be declared by placing the keyword ‘inline’. Invalid !. A function having loop/switch/goto are can’t be inline. Invalid !. A function not returning a value. Some examples of Inline functions.
  • 33.
    Constant Member Functions.A member function that does not have alter any data are known as constant member function. If a member function of a class does not alter any data in the class, then, this function may be declared as a constant member function using the keyword ‘const’. # include <iostream.h> # include <conio.h> class X { int a; public : void assign ( int val) const { a = val; } void setval ( int val ) { a = val; } void out() const { cout << “The Value of A = “ << a; } }; Error !. A const member function does not alter Data. Valid. setval () is not a const member function. So it can alter Data.
  • 34.
    Nesting of MemberFunctions. When a member function is called by another member function, it is called nesting of member function. # include <iostream.h> class student { int roll_no, m1,m2,m3, tot; char name [20]; void cal_total() { tot = m1 + m2 + m3; } public: void input() { cout << “nEnter Name, Roll No & 3 Marks “; cin >> name >> roll >> m1 >> m2 >> m3; cal_total(); } Void out() { cout << “nnTotal Marks = “ << tot; } }; int main() { student a; a.input(); a.out(); } Private cal_tot() can’t be called from main(). The function ‘cal_tot() call from ‘input()’.
  • 35.
    The Scope ResolutionOperator :: Scope Resolution operator is used to distinguish between class members and other names. # include <iostream.h> Int a = 10; class X { int a; public: void X :: out() { cout << “Class member A = “ << a; // or X :: a cout << “Value of Global variable A is “ << :: a; } void X :: assign ( int n ) { X :: a = n; } }; main() { X obj; obj.assign(20); obj.out(); } In this class the full name of variable ‘a’ is ‘X :: a’. The full name of a class member is also called ‘Qualified Name”. The qualified name of out() is X :: out(); Use :: for global variables if they are hidden by a local variable. Qualified Name of member function X :: assign() Qualified Name of member function out() is X :: out() Insidethisclassglobal variable‘a’ishiddenname.
  • 36.
    Using Objects. Whenyou define a class, it does not create objects of that class, rather it only specifies what type of information the objects of this class will be containing. Once a class has been defined its instances (objects) can be created like any other variable, using the class name. # include <iostream.h> class length { int cm,m; public: void input(); void out(); } void length :: out() { cout << “nGiven Length is “ << m << “ mtr and “ << cm << “ cms”; } void length :: input() { cout << “nnEnter the length in Meter & Cm. “; cin >> m >> cm; } Int main() { length a; a.input(); a.out(); } Creating instance of class length.
  • 37.
    We have alreadyknow that the memory space for objects is allocated when they are declared and not when the class is defined. Member functions are created and placed in the memory only once when the class is defined. The memory space is allocated for data members only when the objects are created. No separated space is allocated for member functions. Since all the objects belonging to a class use same functions, there is no separate space for member functions. Thus member functions are created and stored when the class is defined and this memory space can be shared by all instance of that class. Separated memory space is allocated for the data members. Because the data members holds different values for different objects.
  • 38.
    # include <iostream.h> classlength { Int feet, inch; public: void input() { cout << “Enter Feet and Inches “; cin >> feet >> inch; } void out() { cout << “Feet = “ << feet; cout << “Inch =“ << inch; } }obj1, obj2, obj3; Memory for obj1 Feet = 7, inch = 3 Memory for obj2 Feet = 7, inch = 3 Memory for obj3 Feet = 7, inch = 3 ………………………………………… Memory Space for Member Functions ………………………………………… void input () { } void input () { } Separate Memory Space for Data-Members of each Objects. No separate Memory Space for Member Functions. Only one copy of member functions are shared by all objects.
  • 39.
    # include <iostream.h> classlength { Int feet, inch; public: void input() { cout << “Enter Feet and Inches “; cin >> feet >> inch; } void out() { cout << “Feet = “ << feet; cout << “Inch =“ << inch; } }obj1; void main() { length obj2, obj3; cout << “nSize of obj1 is “ << sizeof(obj1); cout << “nSize of obj2 is “ << sizeof(obj2); cout << “nSize of obj3 is “ << sizeof(obj3); cout << “Size of Class Length “ << sizeof (length); } Output: Size of obj1 is : 4 Size of obj2 is : 4 Size of obj2 is : 4 Size of Class Length : 4 The memory space is allocated for data members of each objects. No separated space is allocated for member functions. 2 byte feet + 2 byte inch = 4 byte.
  • 40.
    Array of Objects. Anarray is a collection of elements of same type, that are referenced by a common name. An Array having class type elements is known as Array of Objects. Element of the array can be referenced by saying its position from starting element. The No indicating element's position is called Array Index. Array index start from 0 and are uptill size – 1. Elements are stored in consecutive memory cell. class student { int Roll; float per_marks; char name[20]; } a[10]; 99 100 126 152 178 204 230 256 282 308 334 335 …. A[0] A[1] A[2] A[3] A[4] A[5] A[6] A[7] A[8] A[9] …. Consecutive Memory Cells and its Address. The size of a student is 26 (Roll 2 + per_marks 4 + Name 20 = 26). Here address being start from 100 and will be incremented by 26. 2 bytes Roll No 4 bytes per_marks 20 bytes Name
  • 41.
    # include <iostream.h> classItem { Int item_no; float price; public: void getdata(int n, float p) { item_no = n; price = p; } void putdata() { cout << “n” << item_no << “t” << price; } }; int main() { Item a[10]; int i, itn; float p; for(i=0; i<10; i++) { cout << “nEnter Item No & Price “; cin >> itn >> p; a[i].getdata(itn, p); } for(i=0; i<10; i++) a[i].putdata(); } Declare an array having 10 elements of type class item. a[0] - First element in the Array. a[1] - Second element in the Array. a[2] - Third element in the Array. …… a[9] – 10th element in the Array. A[0].getdata (ino, p); Call the function getdata() in association with a[0]th element, and assign itn in item_no and p in price. Array Index Data member 0th element Item_no = 100 price = 25.75 1st element item_no = 101 price = 30.50 2nd element item_no = 102 price = 15.00 ‘i’ start from 0 and increment by 1. Read item No and price from the user and assign these values in respective data members of a[0], a[1], a[2] … Print data members of successive Array elements a[0], a[1], a[2] … a[9] using a for loop through the accessor function putdata().
  • 42.
    Objects as FunctionArgument. The values passed to a function are called Argument or Parameter. The values given in function calling statement is Actual Argument and the Objects received them at function definition are called Formal Arguments. Like any other data type, an object may also be passed as argument. The object can also be passed both ways By Value and By Reference. Function Call By Value. When an object is passed by value, the function creates its own copy of the object and works with its copy. Therefore any changes made in the object inside the function dol not affect actual object. Int main() void swap (int x, int y) { { int a = 10, b = 20; int z = x; swap (a, b); x = y; y = z; } } Function Call By Reference. When the object is passed by reference, its memory address is passed to the function so that the called function works directly on the orginal object used in the function call. Int main() void swap (int &x, int &y) { { int a = 10, b = 20; int z = x; swap (a, b); x = y; y = z; } }
  • 43.
    # include <iostream.h> #include <conio.h> class length { public: int m, cm; void input(); void out(); }; void length :: input() { cout << "nnEnter Meter & Cm"; cin >> m >> cm; } void length :: out() { cout << "nn " << m << " Meters and “ << cm << " Cms."; } Call By Value. A function add(length l1, length l2) will add 2 length. length add(length l1, length l2) { length l3; l3.m = l1.m + l2.m; l3.cm = l1.cm + l2.cm; if(l3.cm>=100) { l3.m++; l3.cm-=100; } return l3; } int main() { length a, b, c; a.input(); b.input(); a.out(); b.out(); c = add(a,b); c.out(); getch(); } m and cm are public data members. So these can be accessible.
  • 44.
    # include <iostream.h> #include <conio.h> class length { int m, cm; public: void input(); void out(); friend length add (length l1, length l2); }; void length :: input() { cout << "nnEnter Meter & Cm"; cin >> m >> cm; } void length :: out() { cout << "nn " << m << " Meters and “ << cm << " Cms."; } Friend Function. It is possible to grand a nonmember function access to the private members of a class. A friend function has access to all the members of a the class for which it is a friend. By declare a function proceeding with the keyword ‘friend’ within the class, that function become ‘friend’. Here add(length l1, length l2) is a friend of class length. length add(length l1, length l2) { length l3; l3.m = l1.m + l2.m; l3.cm = l1.cm + l2.cm; if(l3.cm>=100) { l3.m++; l3.cm-=100; } return l3; } int main() { length a, b, c; a.input(); b.input(); a.out(); b.out(); c = add(a,b); c.out(); getch(); } By declaring the function add() proceeding with the keyword ‘friend’, it become ‘friend’ of class length. So add() can access m and cm.
  • 45.
    # include <iostream.h> #include <conio.h> # include <string.h> // to use strcpy() class time { int h,m,s; char suf[8]; public: void input(); void out(); friend void change_24hrs(time &t); }; void time :: input() { cout << "nnEnter Hrs, Min and Sec”; cin >> h >> m >> s; cout << “ Suffix AM/PM ?."; cin >> suf; } void time :: out() { cout<<"nn"<<h<<":"<<m<<":"<<s << suf; } void change_24hrs(time &t) { if ( strcmp(t.suf,"PM") == 0 ) { t.h+=12; strcpy(t.suf, " 24 Hrs"); } } int main() { time t; t.input(); t.out(); change_24hrs(t); t.out(); getch(); } Function Call By Reference. When the object is passed by reference, its memory address is passed to the function so that the called function works directly on the orginal object used in the function call. If you remove ‘&’ then it become Call by value. In that case the output would be incorrect. Write this program with and without ‘&’ and see the Difference.
  • 46.
    STATIC CLASS MEMBERS.There are two types of Static Members. (i) Static Data Members. (ii) Static Functions. Static Data members of a Class. Only one copy of data that are shared by all the objects of that class are called Static Data Members. The static data members are usually maintained to store values common to the entire class. Such data will provide access control to some shared resources used by all objects of a class. Since they are associated with the class itself, rather than with any objects they are also known as class variables. You can declare a Static variable preceded with the keyword ‘static’. class X { static int a; ….. }; Static Data Members is different from ordinary Data Members in various respect. 1. There is only one copy of this data maintained for the entire class which is shared by all the objects of that class. 2. It is visible only within the class however its life time is the entire program. Tthe time for which a value remains in the memory is called ‘life time.’ Two things are needed for making a data member static. i) Declare it within the class. ii) Define it outside the class definition.
  • 47.
    # include <iostream.h> #include <conio.h> class student { int Roll_no; char name[20], std[7]; static char school[30]; public: void input(); void output(); }; void student :: output() { cout << "nnName : " << name; cout << "nnRoll No : " << Roll_no; cout << "nnSchool : " << school; } void student :: input() { cout << "nnPls enter Name & Roll No "; cin >> name >> Roll_no; } char student :: school[30] = "VidhyadhiRaja"; int main() { student a,b; a.input(); b.input(); a.output(); b.output(); getch(); } Output. Pls enter Name & Roll No : Raman 100 Pls enter Name & Roll No : Soman 101 Name : Roman Roll No : 100 School : VidhyadhiRaja Name : Soman Roll No : 101 School : VidhyadhiRaja Declared it within the class precede with ‘static’ and also Defined/initialize it outside the class definition Sharing Same Data along several Objects. Static Data are common to all objects.
  • 48.
    Static Member Function. Amember Function that access only the static members of a class may be declared as static. By putting the keyword ‘static’ before the function declaration, member function becomes ‘static’. A Static Member Function is different from other member functions in various respects. A Static Member function can access only static members of the class. A static Member function is invoked by using the class name instead of its objects. class student { ….. static char school[30]; static void assignschool() { Strcpy(school, “”); } }; main() { student :: assignschool(); }
  • 49.
    # include <iostream.h> #include <conio.h> # include <string.h> class student { int Roll_no; char name[20], std[7]; static char school[30]; public: static void assign_school(char nam[]); void input(); void output(); }; void student :: input() { cout << "nnPls enter Name & Roll No "; cin >> name >> Roll_no; } void student :: assign_school(char nam[]) { strcpy(school, nam); } void student :: output() { cout << "nnName : " << name; cout << “nnRoll No ::“ << Roll_no; cout << "nnSchool : " << school; } char student :: school[30]; int main() { student a,b; student :: assign_school ("V R. V. P"); a.input(); b.input(); a.output(); b.output(); getch(); } Putting the keyword ‘static’ before the function declaration, it becomes ‘static’. Static Member function can access only static members of the class. static Member function is invoked by using the class name instead of its objects.
  • 50.
    A class definitiondoes not create Objects. Objects are to be created separately. The Member functions are commonly created and stored in the memory for all Objects. The objects are created separately to store their data members. The Objects can be passed to as well as returned from function. The static data members are global variables for its class type objects. These are commonly shared by all the objects of that class type. The static member functions are the functions that can access only the static data. The ordinary member functions can access both static as well as ordinary members of a class.