Documente Academic
Documente Profesional
Documente Cultură
cl ob2; //invalid
}
In the above example the class cl is available only within main()
function therefore it can not be obtained in the function
function().
A object is said to be a global object if it is
declared outside all the function bodies it
means the object is globally available to all the
function in the code.
A global object can only be declared using global
class type.
A object is said to be a local object if it is
declared within the body of any function it
means the object is available within the function
and can not be used from other function.
A local object can be created from both class
types : global as well as local.
my_class
{
int a;
public :
void fn()
{
a=5;
cout<<The answer is <<a;
}
};
// * Global object *//
my_class ob1;
void kv()
{
//* Local object *//
my_class ob2;
}
void main()
{
ob1.read();
//* ob1 can be used as it is
global *//
ob2.read();
//* ob2 can not be used as
it is local *//
}
Nested Classes
When a class declared within another class then class declared within
(inside/inner class) is called Nested class and the outer class is called
Enclosing class.
class encl {
int a;
class nest{
};
public :
int b;
};
In the given example encl is an enclosing class and nest is the nested
class. The object of nested class can only be declared in enclosed class.
Object as Function Argument-
An object can be passed both ways:
i) By Value
When an object is passed by value, the function creates
its own copy of the object to work with it, so any
change occurs with the object within the function does
not reflect to the original object.
ii) By Reference
when we use pass by reference then the memory
address of the object passed to the function therefore
the called function is directly using the original object
and any change made within the function reflect the
original object.
class my_class {
public :
int a;
void by_value(my_class cv)
{ cv.a=cv.a+5;
cout<<"\n After pass by value";
}
void by_ref(my_class &cr)
{ cr.a=cr.a+5;
cout<<"\n After pass by reference";
}
void disp(my_class di)
{
cout<<"The result is "<<di.a;
}};
void main()
{ clrscr();
my_class ob,mc;
ob.a=12;
mc.by_value(ob);
mc.disp(ob);
mc.by_ref(ob);
mc.disp(ob);
getch();
}
Function Returning Object/ class type
function
To return an object from function we have
to declare the function return type as class
type .
For example my_class fn();
Here my_class is the class name and fn() is
the function name.
Constant Member Functions
If a member function of a class does not change any
data in the class then the member function can be
declared as constant member by post fixing the word
const at the time of function declaration.
Example- void fn() const;
Once a member function declared as const, it cannot
alter the data values of the class. Compiler will
generate error message.