Object of a class are similar to variables to structures. A class contain data items and member functions
The principal objective of object oriented programming is putting data and funtions into one class and data hiding.
A class is specified just like a structure with name. The body of the class is enclosed with curly braces and terminated with semicolon. Two keywords are used within the class viz. private and public.
By using keyword private in a class, we can hide data which can be accessed by functions defined within the class
By using keyword public in a class, both data and functions can be accessed by any functions even from outside the class
Generally data is private and functions are public. Reverse may also be true. Member functions need to be defined within the class specification just as inline in function are done. Space in memory is set up only when object are defined in the main() pgm and not during class specification. Member functions are accesisble only through the objects of that class using the class member access operator ".".
eg:
#include<iostream.h>
class sample
{
private:
int value;
public:
void memfun(int x)
{
value=x;
}
void display()
{
cout<<value;
}
}; // NOTE: CLOSING BRACE AND SEMICOLON
void main()
{
sample a1,a2; // 2 OBJECTS OF SAMPLE CLASS
a1.memfun(1234);
a2.memfun(6789);
cout<<"\n HOME PO BOX no is :";
a1.display();
cout<<"\n OFFICE PO BOX no is :";
a2.display();
}
OUTPUT IS
HOME PO BOX no is :1234
OFFICE PO BOX no is :6789
eg: A class with multiple data objects
#include<iostream.h>
class student
{
private:
int register_no;
char grade;
float fees;
public:
void assign(int x, char y, float z)
{
register_no= x;
grade= y;
fees=z;
}
void display()
{
cout<<"\nRegister number :"<<register_no;
cout<<", Grade obtained :"<<grade;
cout<<", Fees :$"<<fees;
}
};
void main()
{
student s1;
s1.assign(1234,'A+',50);
s1.display();
}
OUTPUT
Register number :1234, Grade obtained : A+, Fees :$50


Sign In
Create Account

Back to top









