Sunday, 22 January 2023

Defining member functions in C++

 Defining member functions in C++

In C++ when we create a function inside a class it is known as member function. A member function in C++ can be defined in two different ways:

  • We can define function inside the class i.e. body of the member function will be provided inside class definition.

  • We can declare function inside the class i.e. its prototype will be declared inside the class definition but its definition i.e. its body will be defined outside the class.
If we know that our function definition is small in length, it does not contain any loops or any other complex statements then we may define member function inside the class. If a member function is defined inside a class then compiler may try it treat it as inline function. As a result all the advantages and drawbacks of inline functions will come along.

Example:


Output:

a = 10

b = 20

Click Here to Download Source Code

Another way is to give prototype of function inside the class i.e. function can be declared inside the class and its definition is provided outside the class. If we define a member function outside the class then we have to use scope resolution operator to differentiate it from functions of other classes.

Example:


Output:

a = 10

b = 20

Click Here to Download Source Code

In case we declare member function inside the class then location of its declaration will decide its visibility i.e. it is public, private or protected. In our case both member functions are declared in public section so they are public in nature.



#c++ #cpp #scoperesolution #memberfunctions #cplusplus #functions #definition #coding #codingmadeasy #codingmadeasy #clanguage #cprogramming #java #javaprogramming #datastructure #algorithms #complexity #coding #codeforfun #codinglife #coderlife #programming #program #computerscience #it #technology #ugc #gate #gate #nta #net

No comments:

Post a Comment