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 is similar to structures in C-language, but with the major difference:
S.No. | Structure | Class |
---|---|---|
By default members of the structure is 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. |
Class is a user-defined data type, use for wrapping different types of data and functions together. 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> #include<conio.h> class student { private: //variable declaration int rollno; char name[20]; public: //function declaration void input(); void output(); }; //function definition 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() { clrscr(); student s; //object created s.input(); //calling class function input s.output(); //calling class function output getch(); }