Classes also have same syntax as structures but the difference is that in a class the members are private by default, while in a structure the are public by default.
A Simple Class
Here is the 1st program related to the classes that contain a class and two objects of that class.
Copy this program and run in your compiler and understand it.
#include<iostream.h> //if you are using C then use <stdio.h>
class student //class student
{
private:
int roll;
public:
void setdata(int r) //member function to setdata
{roll=r;}
void showdata(); //member function to display data
{cout<<roll no. is= "<<roll<<endl;} //use printf(""); in C instead of cout<<;
};
void main()\
{
clrscr();
student s1,s2; //define two objects of class student
s1.setdata(9); //call member function to set data
s2.setdata(10);
s1.showdata(); //call member function to display data
s2.showdata();
getch();
}
No comments:
Post a Comment