×

C++ Tutorial

C++ Data types

C++ Operators & Keywords

C++ Conditional Statements

C++ Functions

C++ 'this' Pointer, References

C++ Class & Objects

C++ Constructors & Destructors

C++ Operator overloading

C++ 11 (Advance C++)

C++ Preparation

C++ Header Files & Functionsr

Data Structure with C++

C++ - Miscellaneous

C++ Programs

Defining member function outside of the class in C++

A member function can be defined outside of the class too; here we will learn how to define a class member function inside and outside of the class?

First see, how we can define a function inside a class:

Consider the following syntax

class class_name
{
    private:
        declarations;
    public:
        function_declaration(parameters)
        {
            function_body;
        }
};

Example

Consider the following example, here we are defining member functions inside the class definition:

#include <iostream>
using namespace std;

class Example {
 private:
  int val;

 public:
  // function to assign value
  void init_val(int v) { val = v; }
  // function to print value
  void print_val() { cout << "val: " << val << endl; }
};

int main() {
  // create object
  Example Ex;
  Ex.init_val(100);
  Ex.print_val();

  return 0;
}

Output

val: 100

In the above example, public member functions init_val() and print_val() are defined inside the class definition.


Defining member function outside of the class definition

A public member function can also be defined outside of the class with a special type of operator known as Scope Resolution Operator (SRO); SRO represents by :: (double colon)

Syntax

Consider the following syntax to define member functions outside of the class definition:

return_type class_name::function_name(parameters)
{
    function_body;
}

Example of defining member function outside of the class definition

Consider the following example, here we are defining member functions outside of the class definition:

#include <iostream>
using namespace std;

class Example {
 private:
  int val;

 public:
  // function declarations
  void init_val(int v);
  void print_val();
};
// function definitions
void Example::init_val(int v) { val = v; }

void Example::print_val() { cout << "val: " << val << endl; }
int main() {
  // create object
  Example Ex;
  Ex.init_val(100);
  Ex.print_val();

  return 0;
}

Output

val: 100

Related Tutorials

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.