2)Classes and objects
2)Classes and objects
class className {
// some data
// some functions
};
eg:
class Student
{
public:
int id; //field or data member
className objectVariableName;
eg:
Student s1;
eg:
C++ Object and Class Example
#include <iostream.h>
class Student {
public:
int id;//data member (also instance variable)
char name[];//data member(also instance variable)
};
int main() {
Student s1; //creating an object of Student
s1.id = 201;
s1.name = "Sonoo Jaiswal";
cout<<s1.id<<"\n";
cout<<s1.name<<endl;
return 0;
}
----------- array of objects --------------
#include<iostream.h>
#include<conio.h>
class student{
public:
int id;
float tamil;
void display(){
cout<<"\nid="<<id;
cout<<"\nTamil="<<tamil;
}
};
void main(){
student s[2];
int i;
clrscr();
for(i=0;i<=1;i++){
cout<<"\n-----Enter student "<<(i+1)<<"Details --------" ;
cout<<"\nEnter the ID:";
cin>>s[i].id;
cout<<"\nEnter the mark:";
cin>>s[i].tamil;
}
for(i=0;i<=1;i++){
cout<<"\n---- student "<<(i+1)<<" details are ------";
s[i].display();
}
getch();
}
o/p:
-----Enter student 1 Details-------
Enetr the id:1
Enter the Mark:100
Enetr the id:2
Enter the Mark:100
-----student 1 Details are-------
id=1
mark=100
id=2
mark=100
#include<iostream.h>
#include<conio.h>
class student{
public:
int id;
char name[100];
float tamil,english,maths,science,social,tot,percentage;
void display(){
cout<<"\nid="<<id;
cout<<"\nName="<<name;
cout<<"\nTamil="<<tamil;
cout<<"\nEnglish="<<english;
cout<<"\nMaths="<<maths;
cout<<"\nScience="<<science;
cout<<"\nSocial="<<social;
cout<<"\n Total ="<<tot;
cout<<"\nPercentage="<<percentage;
}
void result(){
tot=tamil+english+maths+science+social;
percentage=(tot/500)*100;
}
};
void main(){
student s[2];
int i;
clrscr();
for(i=0;i<=1;i++){
cout<<"\n-----Enter student "<<(i+1)<<"--------" ;
cout<<"\nEnter the ID:";
cin>>s[i].id;
cout<<"\nEnter the name: ";
cin>>s[i].name;
cout<<"\nEnter the Tamil mark:";
cin>>s[i].tamil;
cout<<"\nEnter the English mark:";
cin>>s[i].english;
cout<<"\nEnter the Maths mark:";
cin>>s[i].maths;
cout<<"\nEnter the Science mark:";
cin>>s[i].science;
cout<<"\nEnter the Social mark:";
cin>>s[i].social;
}
for(i=0;i<=1;i++){
cout<<"\n---- student "<<(i+1)<<" details are ------";
s[i].result();
s[i].display();
}
getch();
}