How are member functions (Class) different from other global functions (in Class program) in Object Oriented Programming?
Member functions and a non-member function are entirely different from each other in Object Oriented Programming.
A member function of any class has full access to the private data members of that class without taking the help of an object of that class and for calling member functions in main() then dot operator (.) is required along with an object. A member function of the class cannot be called without an object outside the class but a non-member function cannot access the private members of a class. Non-member function is called in main( ) without using an object of a class.
Explanation with the help of a C++ program
Program Code:
#include<iostream>
using namespace std;
// declaration and definition of global function
void display()
{
cout<<"Global Function ";
}
// declaration and definition of class with one data member and two member functions
class A
{
// data members a
int a;
public:
// member function accessing data member a
void getdata()
{
cout<<"Enter the value of a : ";
cin>>a;
cout<<endl;
}
// member function accessing data member a
void display()
{
cout<<"The entered value of a : ";
cin>>a;
cout<<endl;
}
};
// main() function definition
int main()
{
// class object declaration
A obj;
// member function of class access with object and dot(.) operator
obj.getdata();
obj.display();
// global function are used without any class object in main()
display();
return 0;
}
The program output is tested on www.jdoodle.com
Output:
Enter the value of a : 6
The entered the value of a : 6
Global Function
Thanks
Mukesh Rajput
Post A Comment:
0 comments: