C++ Defining Member Function

One of the class member is member function. A function declared as a member of the class is called a c++ member function. There are many types of member functions and different ways to define the c++ member functions.

Advertisements

Types of C++ member functions

There are many types of member functions for different purpose.

  1. Manager Functions
  2. Accessor Functions
  3. Mutator Functions

Now we discuss each of them briefly.

Manager Functions

The main task of manager member function is to initialize and later destruction of created objects.

e.g. Constructor and De-constructor

Accessor Functions

The private data member of a class cannot be accessed by any other functions. The accessor member function returns the value of the private member.

e.g.

Advertisements
class student{ 
   private:     
      int age;  
   public:     
      get_age(){     
      return age;    
      } 
};

Mutators

The accessor get access to the private member to get the values. The mutator functions modify the data members in a class and usually placed right after the accessors.

e.g.


class sum{  
   private:  
       int a;  
       int b;  
       int total;  
   public:  
       void total(int a, int b) 
       {  
       total = a + b;  
       cout << total << endl; 
       } 
 };

Defining the member function

There are two ways to define the member function.

  1. Inside the class (inline)
  2. Outside the class

Inline function

When the function is defined inside the class it is called an inline function. The inline member functions should be small because they are translated directly.

For example,

class student{  
   int rollno;  
   int name;  
   char grade;  
public:  
   char get_grade{  
        return(grade); 
        } 
};

Member function defined outside the class

Sometimes, the member function is defined outside of the class. But it must be declared inside the class first. The syntax to declare the c++ member function is given below.

Syntax

return-type <class-name> :: <function-name> (arguments) { }

The member function is defined outside of the class using a scope resolution operation (::). Here is an example of function that is defined outside of class.

class student { 
   int rollno;  
   int name;  
   char grade;  
public:  
   char get grade(); 
 }; 
//function definition  
char student::get_grade() {  
     return (grade); 
}

References

  • Balagurusamy. 2008. Object Oriented Programming With C++. Tata McGraw-Hill Education.
  • Maureau, Alex. 21-Jul-2013. Reviewing C++. Alex Maureau.
  • Ravichandran. 2011. Programming with C++. Tata McGraw-Hill Education.7


Advertisements

Ads Blocker Image Powered by Code Help Pro

Ads Blocker Detected!!!

We have detected that you are using extensions to block ads. Please support us by disabling these ads blocker.