Sunday, 31 March 2019

How to Define Functions in C++ (or) Defining member functions in C++

There are 2 ways to define a member function:
  • Inside class definition
  • Outside class definition

1. Defining member function inside class

        you can define a member function in side a class where is declared. It is an easy and straightforward way to define functions in C++. Then the object is used to access such functions. The accessing is depends on access protection type.


    using namespace std;

    class MyClass

    {

        // Access specifier

        public:


        // Data Members

        string name;


        // Member Functions()

        void display()

        {

        cout<<"name is: "<<;name;

        }

    };


    int main() {


        // Declare an object of class MyClass

       MyClass obj1;


        // accessing data member

        obj1.name = "RAMU";


        // accessing member function

        obj1.display();

        return 0;

    } 

2. Defining Member function outside the class definition

     Functions that are declared inside a class have to be defined separately outside the class. Their definition are very much like the normal functions. They should have a function header and a function body. To define a member function outside the class definition we have to use the scope resolution :: operator along with class name and function name.

 Example:

 // C++ program to demonstrate function
// declaration outside class



#include <bits/stdc++.h>
using namespace std;
class MyClass
{
    public:
    string name;
    int id;
    
    // display is not defined inside class definition
    void display();
    
    // show is defined inside class definition
    void show()
    {
        cout << " id is: " << id;
    }
};

// Definition of display using scope resolution operator :: 


void Geeks::display()
{
    cout << "name is: " << name;
}
int main() {
    
    MyClass obj1;
    obj1.name = "xyz";
    obj1.id=15;
    
    // call display()
    obj1.display();
    cout << endl;
    
    // call show()
    obj1.show();
    return 0;
} 

0 comments :

Post a Comment

Note: only a member of this blog may post a comment.

Machine Learning

More

Advertisement

Java Tutorial

More

UGC NET CS TUTORIAL

MFCS
COA
PL-CG
DBMS
OPERATING SYSTEM
SOFTWARE ENG
DSA
TOC-CD
ARTIFICIAL INT

C Programming

More

Python Tutorial

More

Data Structures

More

computer Organization

More
Top