What is a Class
There are many definitions of class. Some of the best definition that define class are :
- Class is used to create user defined data type.
- Class is a template that defines the form of an object.
- Class is first level of encapsulation.
- A class is a data type whose variables are objects.
A class is created by use of the keyword class. The general form of a simple class declaration
is :
class class-name
{
private :
private data and methods
public :
public data and methods
protected :
public data and methods
};
class class name v1,v2,v3....vn;
The private, protected and public are three keywords used to specify the three levels of
access protection.
A class can contain private as well as public members. By default, all items defined in a class
are private.
We will discuss these access specifier in detail later.
v1,v2,v3...vn are the list of variables or objects.
Note :
Do not assign keywords as variable name.
Object :
Object is an instance of class.
In above syntax v1,v2,v3...vn are the objects of class.
Specifically, a class creates a logical framework that defines a relationship between its members. When you declare a variable of a class, you are creating an object. An object has physical existence and is a specific instance of a class. That is, an object occupies memory space, but a type definition does not.
Example :
#include <conio.h>
class Account
{
public:
int account_no;
void display()
{
cout<<"Account number is : " << account_no;
}
};
void main()
{
clrscr();
Account acc;
acc.account_no=121;
acc.display();
getch();
}
Output :
Description :
-We have created a class named Account.
-Inside class we have declared a public variable of int type named account_no.
-We also created a public method named display in which we display the account_no.
-In main() we have created a object named 'acc' of class Account.
-acc.account_no=121 :
dot (.) operator is used to assign the value 121 to the variable account_no.
-At last we have called the display mathod again with (.) operator.
We will discuus more of this dot operator in next topic.
Note :
We created the object inside the main() method. We can also create the object outside the
main() method just after the class declaration.
The following way is also correct :
class Account
{
public:
int account_no;
void display()
{
cout<<"Account number is : "<
}
};
void main()
{
clrscr();
acc.account_no=121;
acc.display();
getch();
}
Output :
Prev NEXT
0 comments:
Post a Comment