Defining Member Functions:
Functions Member functions can be defined in two places:
places: class number
1. Inside the class definition {
2. Outside the class definition.
definition. private:
private:
int a;
The function body is identical in both the cases only
public:
public:
function header is changed.
changed. void getdata()
getdata()
{
1. Inside the class definition “Enter any int number”;
number”;
General form / syntax : cin>>a
cin>>a;
>>a;
}
return data-
data-type function-
function-name ( arguments )
{ void display()
function body;
body; {
} cout<<“Number
cout<<“Number = ”<<a;
”<<a;
}
A member function can defined inside a class.
class. };
Normally small function are defined inside the class
definition and these functions are treated as inline
functions.
functions. channel link : https://www.youtube.com/c/ComputerScienceAcademy7
video link : https://youtu.be/EA57vk31qMk
2. Outside the class definition
Member functions which are not defined inside a class class number
have to be defined separately outside the class.
class. {
private:
private:
General form / syntax : int a;
public:
public:
return data-
data-type class-
class-name : : function-
function-name ( arguments )
void getdata()
getdata();
();
{ void display();
display();
function body;
body; };
}
void number : : getdata()
getdata()
Class – name : : is membership label.
label.
{
It tells complier that the function belongs to the class.
class. cout<<“Enter
cout<<“Enter any int number”;
number”;
The symbol : : is scope resolution operator.
operator. cin>>a
cin>>a;
>>a;
The scope of the function is restricted to the class - name }
specified in header line.
line.
void number : : display()
The functions which are defined outside the class {
definition can be made inline by using the qualifier inline in cout<<“Number
cout<<“Number = ”<<a;
”<<a;
the header line of the function definition.
definition. }
For example:
example: inline void number : : getdata ( );
Memory Allocation for objects
The memory space for member functions is allocated class number
{
when they are defined as a part of class specification.
specification.
private:
private:
All objects belonging to the class uses the same member int a;
functions.
functions. public:
public:
Separate memory locations for the objects are allocated void getdata(int
getdata(int x)
when they are declared.
declared. {
a = x; N1.a
Separate memory locations for the objects are essential
}
because the member variables will hold different data N2.a
values for different objects.
objects. void display()
Common for all object Memory created when {
function defined cout<<“Number
cout<<“Number = ”<<a;
”<<a;
Member function 1 }
Member function 2 };
void main()
Object 1 Object 2 {
Member variable 1 Member variable 1 number N1, N2;
Member variable 2 Member variable 2
N1.getdata(
getdata(10)
10); N1.display()
display();
();
N2.getdata(
getdata(20)
20); N2.display()
display();
();
Memory created when }
object defined