Classes&Objects
Classes&Objects
Object
An Object is an instance of a class. A class is a data
type and an object is its variable.
*The object occupies space in memory during runtime
public:
void initialize()
{count=0;}
void increment()
{count++;}
void decrement()
{ count--;}
int get_count()
{return count;}
}; //end of class
int main()
{
Counter c;
c.initialize();
c.increment();
c.increment();
c.increment();
cout<<endl<<c.get_count();
c.decrement();
cout<<endl<<c.get_count();
return 0;
}
Passing Object as Function
Argument & Returning Object
This Pointer
• Contains the address of current object
• Current object is the object with which the member function is called
It puts the address of the object as the argument with which the member
function is called
The “this ->” is placed before each member data in the definition of the
function, specified without any object name
Example
#include<iostream.h>
Class Where
{
private:
char charray[10]; // occupies 10 bytes
public:
void reveal()//displays the address of current object // void reveal(Where* this){…..}
{ cout<<“\nMY object’s address is “<<this;}
};
// main function
int main()
{
Where w1,w2,w3; //make these objects
W1.reveal(); // this is the pointer of w1 // W1.reveal(&W1);
W2.reveal();// this is the pointer of w2
W3.reveal();// this is the pointer of w3
cout<<endl;
return 0;
}
Uses of this pointer
• When an argument to a class function has the same
identifier as a class field
void main(){
Jack ja;
Jill ji;
ja.setVar(56);
ji.setVar(57);
cout<<“ja.getVar()=“<<ja.getVar();
cout<<“ji.getVar()=“<<ji.getVar();
getId(ja,ji);
}
To be noted…
• Forward Reference
• friend Function declaration is necessary in
both the classes
• This declaration can be placed either in the
private section or the public section of the
class
Use of friend Function
• To access private data of a class from a
non-member function
friend two;
};
class two
{
public:
fun1(one o)
{ cout<<endl<<o.i;}
fun2(one o){cout<<endl<<o.i;}
};
void main()
{
one a;
two b;
b.fun1(a);
b.fun2(a);
}