The most important feature of C++ is the 'class'. A class is an extension of the idea of structures used in C-language. It is a new way of creating and implementing a user-defined data type. C++ classes are similar to structures in C-language, but with the major differences, lets understand that:
S.No. | Structure | Class |
---|---|---|
By default, members of the structure are public | By default, members of the class is private | |
All data declared in structure is public, do not permit data hiding. | Data declared in classes can be private, protected or public. Data hiding is possible. | |
We cannot add 2 objects, eg: object3=object1+object2 is invalid. | Addition of 2 objects is possible, eg. object3=object1+object2 is valid. |
A class is a user-defined data type, use for wrapping different types of data and functions together. A class is a collection of similar type of objects. A class member is accessed when it is instantiated (object created). C++ class declaration syntax:
class class_name { private: variable declaration; function declaration; public: variable declaration; function declaration; };
Example 1: WAP to input student rollno, name and display it using class.
#include<iostream.h>
class student
{
private:
int rollno;
char name[20];
public:
void input();
void output();
};
void student::input()
{
cout<<"Enter Student rollno";
cin>>rollno;
cout<<"Enter Student Name";
cin>>name;
}
void student::output()
{
cout<<"Student name is : "<<name<<endl;
cout<<"Student rollno is : "<<rollno;
}
void main()
{
student s; //object created
s.input(); //calling class function input
s.output(); //calling class function output
}