C++ Class Member Functions

Introduction

A class can store functions.

These are called member functions.

They are mostly used to perform some operations on data fields.

To declare a member function of type void called dosomething(), we write:

class MyClass 
{ 
    void dosomething(); 
}; 

There are two ways to define this member function.

The first is to define it inside the class:

class MyClass 
{ 
    void dosomething() 
    { 
        std::cout << "Hello World from a class."; 
    } 
}; 

The second one is to define it outside the class.

In that case, we write the function type first, followed by a class name, followed by a scope resolution :: operator followed by a function name, list of parameters if any and a function body:


class MyClass //www.  ja v  a2  s.c  o m
{ 
    void dosomething(); 
}; 

void MyClass::dosomething() 
{ 
    std::cout << "Hello World from a class."; 
} 

Here we declared a member function inside the class and defined it outside the class.

We can have multiple members functions in a class.

To define them inside a class, we would write:

class MyClass /* w ww. j  a v a2s .  c  o m*/
{ 
    void dosomething() 
    { 
        std::cout << "Hello World from a class."; 
    } 
    void dosomethingelse() 
    { 
        std::cout << "Hello Universe from a class."; 
    } 
}; 

To declare members functions inside a class and define them outside the class, we would write:

class MyClass /*from  w ww.  ja  v  a2 s.  c o m*/
{ 
    void dosomething(); 
    void dosomethingelse(); 
}; 

void MyClass::dosomething() 
{ 
    std::cout << "Hello World from a class."; 
} 

void MyClass::dosomethingelse() 
{ 
    std::cout << "Hello Universe from a class."; 
} 



PreviousNext

Related