Member Functions in Classes

Member Functions in Classes

A class is collection of data members and member functions. Member functions of a class are used to process the data members of the class. These member functions of a class are declared within the class but can be defined either in the class or outside the class as explained below.


Defining Member Function outside a Class

The following example shows that how a member function can be declared in the class but defined outside the class.

declared

In the example given above, member function speak() is declared inside the class Person at line 11 and defined outside the class at line 13. It is also important to note that while defining the function outside the class the member function is preceded by a scope resolution operator (::) while the scope resolution operator is preceded by the class name, so the syntax becomes as below.

data-type class-name::member-function-name

Defining Member Function Inside a Class

The following example shows that how a member function can be declared and defined within the class.

inside

This approach is more straight forward and also used in some other programming languages like Java and C#. It lessens the complexity and there is no need to use scope resolution operator (::) in this case.

It is important to note that main function remains same whether the member function is defined within the class or outside the class.

More Related Articles For You

    C++ Tutorial

    C++ Quizzes