Saturday, May 12, 2007
What is Object?
Object is like a variable as we create with built-in datatypes. Object is an instance of class.
Object has state,behavior and identity.
state - value of data member at any point of time
behaviour - how object performing a task, it comes from definition of member functions.
identity - name of object.
How to create Object?
Syntax:
class-name object-name;
or
class-name object-name1,object-name2,....;
Suppose we have to create object(s) of class Circle :
Circle c; //One object created
or
Circle c1,c2; //Two objects created
How to call a member function?
Syntax :
object-name.member-function-name();
for example we want to set radius of object c , we have to call a member function SetRadius(int) :
->
c.SetRadius(12);
in same way
int area = c.GetArea();
and so on....
Class Members :
Data Member
Member Function
Members must be declared/defined within class definition.
A member can not be declared twice in the class definition.
Now let's assemble all the pieces together to make it meaningful..
//class definition
class A
{
//data member
int i;
int j;
//member function
int getI() //definition of member function
{
return i;
}
void setI(int a) //definition of member function
{
i = a;
}
};
int main()
{
A aObj; //Creation of object
aObj.setI(20); //calling member function
cout<<aObj.getI(); //calling member function
}