Introduction:
Defining a class means creating user defined data type and it behaves like the built-in data types of programming languages. A class serves as a blue print or a plan or a template for an object. It specifies what data and what functions will be included in objects of that class. Once a class has been defined, we can create any number of objects belonging to that class. An object is an instance of a class. A class binds the data and its associated functions together. It allows the data to be hidden, if necessary, from external use.
Declaration of Class:
Class declaration describes the type and scope of its members. Syntax for class declaration is like
class class_name
{
private:
variable declaration;
function declaration;
public:
variable declaration;
function declaration;
};
an example:
class box
{
private:
float len, br, height;
public:
void get_data();
float volume();
};
Here, class is c++ keyword; class_name is name of class defined by user. The body of class enclosed within braces and terminated by a semicolon. The class body contains the declaration of variables and functions. These variables and functions are known as class members (member variables and member functions). Again, keyword private and public within class body specifies the visibility mode of variables and functions i.e. they specify which of the members are private and which of them are public. The class members that have been declared as private can be accessed only from within the class but public members can be accessed from outside of the class also. Using private declaration, data hiding is possible in C++ such that it will be safe from accidental manipulation. The use of keyword private is optional. By default, all the members are private. Usually, the data within a class is private and the functions are public. C++ provides a third visibility modifier, protected, which is used in inheritance. A member declared as protected is accessible by the member functions within its class and any class immediately derived from it. (The detail will be described in another chapter inheritance)
A class binds data and functions together into a single class-type variable, known as encapsulation.
No comments:
Post a Comment