Member functions in C++

In a C++,  we can use the function within the classes. These functions are called as a member function. It can be public ,private & protected.

Public member function: in a below program we have created a public function which can be accessed from outside of class.

Output

Private member function:  in a below program we have created a private function which can’t be accessed from outside of class.

Output

Description: when we compile this program we will get an error message. Because show() function cant be access from main() because it is a private member function.

How to access private member function

 We can access private member function from public member function. In the below program we have created one public function display() and one private function show() and we can call the show() from within the display().

Output

Define a member function outside of the class

In a C++ language we can define a function inside  as well as outside of the class. To define a function a function outside of the class syntax is:

Syntax:

Datatype class_name :: function name

Output

In the above program we have declare two function inside class and define outside of the class.

a private member function outside of the class

In a below program we have define a private function display() outside of the class which can’t be accessed from outside of class. If we try to access then we will get an error message.

Output

Solution of above program: We can access private member function from public member function. In the below program we have created one public function show() and one private function display() and we can call the display() from within the show().

OUTPUT

Access Private Data Member/Variable

In a C++ we can access private data member within the class. It can’t be used outside of the class.

Output

Note: we can’t access private data member outside of the class. The private data can be accessed by only member function and friend  function of that class. 

Solution of above program: The private data can be accessed by only member function and friend  function of that class. 

Output

Example. Write a C++ program to create a class and member function & find the factorial of the number given by user.

Output

Categories C++