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.
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.
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
- What is C++
- C++ and Object Oriented Programming OOPS concepts
- Syntax and Structure of C++ program
- Data Types in C++
- C++ Variables
- Types of operators in C++
- Decision making in C++
- C++ Loop Types
- Storage Classes in C++
- Functions in C++
- Classes and Objects in C++
- Access controls in C++ Classes
- Defining Class and Object in C++
- Accessing Public and Private Data Members in C++
- Types of Member Functions in C++
- Inline Functions in C++
- Namespaces in C++
- Function Overloading in Classes in C++
- Constructors and Destructors in C++
- Static Keywords in C++
- Const Keyword in C++ Programming
- References in C++
- Copy Constructor in C++
- Pointer to Members in C++ Classes
- Introduction to Inheritance
- Types of Inheritance
- Order of Constructor Call in Inheritance
- Upcasting in C++
- Function Overriding in C++
- Virtual Functions in C++
- Abstract Class and Pure Virtual Functions in C++
- Virtual Destructors in C++
- Operator Overloading in C++
C++ Tutorial
C++ Quizzes