<<

C++ CLASSES AND OBJECTS

 The data and functions (procedures to manipulate the data) are bundled together as a self-contained unit called an object.  A class is an extended concept similar to that of structure in C programming language;  In C++ programming language, class describes both the properties (data) and behaviors (functions) of objects. Classes are not objects, but they are used to instantiate objects.  The mechanism that allows you to combine data and the function in a single unit is called a class.  Once a class is defined, you can declare variables of that type.  A class variable is called object or instance.  In other words, a class would be the data type, and an object would be the variable.  Classes contain data known as members and member functions.

HOW TO WRITE A CLASS:

 A class is specified with a name after the keyword class.  The starting flower brace symbol '{'is placed at the beginning of the code.  Following the flower brace symbol, the body of the class is defined with the member functions data.  Then the class is closed with a flower brace symbol '}' and concluded with a colon ';'.  There are different access specifiers for defining the data and functions present inside a class.  Classes are generally declared using the keyword class, with the following format: class class_name { private: members1; protected: members2; public: members3; };  Where class_name is a valid identifier for the class.  The body of the declaration can contain members, that can be either data or function declarations.  The members of a class are classified into three categories: private, public, and protected.  Private, protected, and public are reserved words and are called member access specifiers.

Access specifiers:

 Access specifiers are used to identify access rights for the data and member functions of the class.  There are three main types of access specifiers in C++ programming language: 1. Private 2. Public 3. Protected  Private members of a class are accessible only from within other members of the same class.  we cannot access it outside of the class. Protected members are accessible from members of their same class and also from members of their derived classes.  Public members are accessible from anywhere where the object is visible  A private member within a class denotes that only members of the same class have accessibility.  The private member is inaccessible from outside the class.  Public members are accessible from outside the class.  A protected access specifier is a stage between private and public access.  If member functions defined in a class are protected, they cannot be accessed from outside the class but can be accessed from the derived class.  When defining access specifiers, the programmer must use the keywords: private, public or protected when needed, followed by a semicolon and then define the data and member functions under it.

Example : class student { private : int rollno; float marks; public: void getdata() { cout<<"Enter Roll Number : "; cin>>rollno; cout<<"Enter Marks : "; cin>>marks; } void displaydata() { cout<<"Roll number : "<

int main ( ) { clrscr( ); item one; // object declaration one.codeno=123; // member initialization one.price=123.45; one.qty=150; } Access Limits of Class Members Access specifiers Access permission Class Class object members public allowed allowed private allowed disallowed protected allowed disallowed 2.3 DEFINING MEMBER FUNCTIONS  The member function must be declared inside the class.  They can be defined in a) private or public section b) inside or outside the class.  The member functions defined inside the class are treated as inline function.  If the member function is small then it should be defined inside the class, otherwise it should be defined outside the class.  If function is defined outside the class, its prototype declaration must be done inside the class.  While defining the function, scope access operator and class name should precede the function name.  The following program illustrates everything about member functions and how to access private member of the class. 2.3.1 Member Function inside the Class  Member function inside the class can be declared in public or private section.  The following program illustrates the use of member function inside the class in public section. 2.3.2 Private member function  To execute private member function it must invoked by public member function of the same class.  A member function of a class can invoke any other member function of its own class.  This method of invoking other member function is known as nesting of member function. 2.3.3 Member Function outside the Class  If a function is small is should be defined inside the class and if larger it must be defined outside the class.  To define a function outside the class the following care should must be taken.  The prototype of function must be declared inside the class.  The function name must be preceded by name and its return type separated by scope access operator. Defining Member Function of Class  Member functions defined inside a class this way are created as inline functions by default.  It is also possible to declare a function within a class but define it elsewhere.  Functions defined outside the class are not normally inline. When we define a function outside the class we cannot reference them (directly) outside of the class.  In order to reference these, we use the scope resolution operator, ::(double colon). In this example, we are defining function getdata outside the class: void student :: getdata() { cout<<"Enter Roll Number : "; cin>>rollno; cout<<"Enter Marks : "; cin>>marks; }  The following program demonstrates the general feature of classes.  Member function initdata() is defined inside the class.  Member funcitons getdata() and showdata() defined outside the class. class student //specify a class { private : int rollno; //class data members float marks; public: void initdata(int r, int m) { rollno=r; marks=m; } void getdata(); //member function to get data from user void showdata();// member function to show data };

void student :: getdata() { cout<<"Enter Roll Number : "; cin>>rollno; cout<<"Enter Marks : "; cin>>marks; }

void student :: showdata() { cout<<"Roll number : "<

int main() { student st1, st2; //define two objects of class student st1.initdata(5,78); //call member function to initialize st1.showdata(); st2.getdata(); //call member function to input data st2.showdata(); //call member function to display data return 0; }  A class definition starts with the keyword class followed by the class name  The class body, enclosed by a pair of curly braces  A class definition must be followed either by a semicolon or a list of declarations.  For example we defined the Box data type using the keyword class as follows: class Box { public: double length; // Length of a box double breadth; // Breadth of a box double height; // Height of a box }; 2.3.4 CHARACTERISTICS OF MEMBER FUNCTIONS (1) The difference between member and normal function is that the former function can be invoked freely where as the latter function only by using an object of the same class. (2) The same function can be used in any number of classes. This is possible because the scope of the function is limited to their classes and cannot overlap one another. (3) The private data or private function can be accessed by public member function. Other functions have no access permission. (4) The member function can invoke one another without using any object or dot operator. 2.4 MEMBER VARIABLES AND FUNCTIONS (1) Static Member Variables  We have noticed earlier that each object has its separate set of data member variables in memory.  The member functions are created only once and all objects share the functions.  No separate copy of function of each object is created in the memory like data member variables.  It is possible to create common member variables like function using the static keyword.  Once a data is declared as static, only one copy of that member is created for the whole class.  The static is a keyword used to preserve value of a variable.  When a variable is declared as static it is initialized to zero.  A static function or data element is only recognized inside the scope of the present class. Syntax: Static ; Static ;  The class and scope of the static member variables is defined outside the class declaration for the following reasons. 1) The static data members are associated with the class and not with any objects. 2) The static data members are stored individually rather than an element of an object. 3) The static member variable must be initialized otherwise the linker will generate an error. 4) Only one copy of static member variables is created for the whole class for any number of objects. 5) All the objects have common static data member. 2.4.1 STATIC OBJECT  The object is a composition of one or more member variables.  There is a mechanism called constructor to initialize member variables of the object to desired values.  The keyword static can be used to initialize all class data member variables to zero.  Declaring object itself as static can do this.  Thus, all its associated members get initialized to zero.  The following program illustrates the working of static object. Example program to declare static object # include # include class bita { private: int c; int k; public : void plus( ) { c+=2; k+=2; } void show( ) { cout <<" c= "<

cout <<" k= "<

ALGORITHM: STEP 1: Start the program. STEP 2: Declare the class name as Stat with data member s and member functions. STEP 3: The constructor Stat() which is used to increment the value of count as 1 to to assign the variable code. STEP 4: The function showcode() to display the code value. STEP 5: The function showcount() to display the count value. STEP 6: Stop the program. PROGRAM: #include #include

class stat { int code; static int count;

public: stat() { code=++count; } void showcode() { cout<<"\n\tObject number is :"<

2.5 ARRAY OF OBJECTS  An array of variables of type “class” is known as "Array of objects".  The "identifier" used to refer the array of objects is an user defined data type.  Arrays are collection of similar data types.  Arrays can be of any data type including user-defined data type, created by using struct, class and typedef declarations.  We can also create an array of objects.  The array elements are stored in continuous memory locations  Consider the following example: class player { private: char name [20]; int age; public: void input (void); void display (void); }; In the example given above player is a user-defined data type and can be used to declare an array of object of type player. Each object of an array has its own set of data variables. player cricket[5]; player football[5]; player hockey[5]; As shown above, arrays of objects of type player are created. The array cricket[5] contains name, age and information for five objects

Example program:

#include const int MAX =100; class Details { private: int salary; float roll; public: void getname( ) { cout << "\n Enter the Salary:"; cin >> salary; cout << "\n Enter the roll:"; cin >> roll; } void putname( ) { cout << "Employees" << salary << "and roll is" << roll << '\n'; } }; void main() { Details det[MAX]; int n=0; char ans; do{ cout << "Enter the Employee Number::" << n+1; det[n++].getname; cout << "Enter another (y/n)?: " ; cin >> ans; } while ( ans != 'n' ); for (int j=0; j

Result: Enter the Employee Number:: 1 Enter the Salary:20

Enter the roll:30 Enter another (y/n)?: y Enter the Employee Number:: 2 Enter the Salary:20

Enter the roll:30 Enter another (y/n)?: n  In the above example an array of object "det" is defined using the user defined data type "Details".  The class element "getname()" is used to get the input that is stored in this array of objects and putname() is used to display the information.

2.6 FRIEND FUNCTIONS  A friend function is used for accessing the non-public members of a class.  A class can allow non-member functions and other classes to access its own private data, by making them friends.  Thus, a friend function is an ordinary function or a member of another class. C++ allows a mechanism, in which a non-member function has access permission to the private members of the class.  This can be done by declaring a non-member function friend to the class whose private data is to be accessed. Here friend is a keyword.  Consider the following example: class ac { private: char name [15]; int acno; float bal; public: void read( ); friend void showbal( ); };  The keyword friend must precede the function declaration whereas function declarator must not.  The function can be defined at any place in the program like normal function.  The function can be declared as friend function in one or more classes.  The keyword friend or scope access operator must not precede the definition of friend function.  The declaration of friend function is done inside the class in private or public part and a function can be declared as friend function in any number of classes.  These functions use objects as arguments. Need for Friend Function:  When a data is declared as private inside a class, then it is not accessible from outside the class.  A function that is not a member or an external class will not be able to access the private data.  A programmer may have a situation where he or she would need to access private data from non-member functions and external classes.  For handling such cases, the concept of Friend functions is a useful tool.

Some important points to note while using friend functions in C++:  The keyword friend is placed only in the function declaration of the friend function and not in the function definition.  It is possible to declare a function as friend in any number of classes.  When a class is declared as a friend, the friend class has access to the private data of the class that made this a friend.  A friend function, even though it is not a member function, would have the rights to access the private members of the class.  It is possible to declare the friend function as either private or public.  The function can be invoked without the use of an object.  The friend function has its argument as objects, seen in example below.

Example Program for Friend Function ALGORITHM: STEP 1: Start the program. STEP 2: Declare the class name as Base with data members and member functions. STEP 3: The function get() is used to read the 2 inputs from the user. STEP 4: Declare the friend function mean(base ob) inside the class. STEP 5: Outside the class to define the friend function and do the following. STEP 6: Return the mean value (ob.val1+ob.val2)/2 as a float. STEP 7: Stop the program. PROGRAM: #include #include class base { int val1,val2; public: void get() { cout<<"Enter two values:"; cin>>val1>>val2; } friend float mean(base ob); // friend function declaration }; float mean(base ob) { return float(ob.val1+ob.val2)/2; } void main() { clrscr(); base obj; obj.get(); cout<<"\n Mean value is : "<

2.7 OVERLOADING MEMBER FUNCTION

 Function is defined with multiple definitions with in the class body. Example: Class { Private: int length, breadth,area; Public: Void getdata() { Cout<<”Length value:”; Cin>>Length; Cout<<”Breadth:”; Cout<> breadth; Area=breadth*length; }

Void showdata(); { Cout<<”length”<

Void main() { Rectangle r1,r2; Cout<<”Enter the 1details:”; r1.getdata(); r1.showdata();

Cout<<”Enter the 2details:”; r2.getdata(); r2.showdata(); } Output: Enter the 1 detail: Length value: 5 Breadth value: 4 Length:5 breadth: 4 the area is :20 Enter the 2detail: Length value: 4 Breadth value: 2 Length:5 breadth: 4 the area is :8