Accessing a member of class
There are two ways to access a data member and member function of a class.
But mainly there are two ways which are used to access data member and member function.
This can be done by using the dot (.) operator. This dot operation is also called as relation
operation.
The general format is as follows :
Way 1 :
The first way is to assign the values to the data members directly with the help of objects :
#include <iostream.h>
#include <conio.h>
class Student
{
public:
int rollno;
float fee;
};
void main()
{
clrscr();
Student student1;
Student student2;
student1.rollno=4;
student1.fee=5000;
student2.rollno=8;
student2.fee=5000;
cout<<"Student1 rollno is : " << student1.rollno;
cout<<"\nStudent1 fee is : " << student1.fee;
cout<<"\n\nStudent2 rollno is : " << student2.rollno;
cout<<"\nStudent2 fee is : " << student2.fee;
getch();
}
Output :
Description :
In this example we assign the values of class variables that is data members directly by using
the dot operator with the help of object :
student1.rollno=4;
student1.fee=5000;
Here student1 is the object that is created from Student class and roono, fee are the data
members of the class.
Note :
This way can be only implemented when the data members are declared as public.
Note that the default access specifier is private.
Example :
#include <iostream.h>
#include <conio.h>
class Student
{
//By default members are private
int rollno;
float fee;
};
void main()
{
clrscr();
Student student1;
Student student2;
//Following all lines gives error since now the data members are private.
student1.rollno=4; //error
student1.fee=5000; //error
cout<<"Student1 rollno is : " << student1.rollno; //error
cout<<"\nStudent1 fee is : " << student1.fee; //error
getch();
}
This way is not mostly used. The Way 2 should be used instead.
Way 2 :
Access data members of class through member function that is method :
#include <iostream.h>
#include <conio.h>
class Student
{
private:
int rollno;
float fee;
public:
void setdata(int rn, float f)
{
rollno=rn;
fee=f;
}
void display()
{
cout<<"Rollno is : " << rollno;
cout<<"\nFee is : " << fee;
}
};
void main()
{
clrscr();
Student stud;
stud.setdata(4,5000); //value is passed as argument in method
stud.display();
getch();
}
Output :
Description :
In this example we pass the values with th help of methods by passing the values as arguments
in the method.
Prev NEXT
0 comments:
Post a Comment