Sie sind auf Seite 1von 9

Classes and Objects

Specifying a Class
A class is an extension of the idea of structure used in C. It is a new way of creating and implementing a user-defined data type. 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.

Class specification
Class Declaration: - describes the type and scope of its members. Class function definitions: - describes how the class functions are implemented.
General form of Class Declaration class class_name { Private: variable declarations; function declarations; Public: variable declarations; function declarations; };

The class declaration is similar to the struct declaration. The keyword class specifies, that what follows is an abstract data of type class_name. The body of the class is enclosed within braces {} and terminated by a semicolon(;). The class body contains the declaration of variables and functions. These variables and functions are collectively called class members: - private and public.

Defining Member Functions


Outside the class definition: - Member functions that are declared inside a class have to be defined separately outside the class. Inside the class definition : - Member function is to replace the function declaration by the actual function definition inside the class

Syntax
Outside the class definition: Return_type class_name :: function_name (arg) { function body; }
Inside the class definition: class abc { //by default private Int x,y; //variables declaration Public: void getdata(int a, int b); //declaration void putdata(void) //definition inside the class { cout << x << \n; cout << x << \n; } };

Accessing Class Members


The private data of a class can be accessed only through the member functions of that class. The main() cannot contain statements that access x and y directly. Format for calling a member function:object_name.function_name (arg); eg: - x.avg(100, 65.5);

WAP to find the average of three numbers using classes


#include<iostream.h> #include<conio.h> class abc { //by default private int x,y,z,a; //variables declaration public: //member function void avg(); //function declaration cout << \n Enter the values of x, y, z; cin >> x >> y >> z; a = (x+y+z)/3; cout << \n The average is: << a; }; void main() output: Enter the values of x, y, z 3 { abc btech; 5 btech.avg(); 4 getch(); The average is: 4 }

THANKS!!!

Das könnte Ihnen auch gefallen