Skip to content

Defining member functions

🔷 What Are Member Functions?

Member functions are functions that are defined inside a class and can access the data members (variables) of that class. They define the behavior of the objects created from the class.

Member functions can be:

  • Defined inside the class
  • Defined outside the class using the scope resolution operator ::

🔷 Syntax: Defining Member Functions

✅ Inside the Class (Inline Definition)

class Example {
public:
void display() {
cout << "Hello from inside the class!" << endl;
}
};

✅ Outside the Class (Using Scope Resolution Operator ::)

class Example {
public:
void display(); // Function declaration inside class
};

void Example::display() { // Function definition outside class
cout << "Hello from outside the class!" << endl;
}

🔷 When to Define Inside vs Outside

Inside ClassOutside Class
Automatically treated as inlineNormal function, not inline by default
Suitable for small/simple functionsSuitable for large/complex functions
Keeps all code in one placeHelps keep class definition clean and short

🔷 Example: Defining Member Functions (Both Ways)

#include <iostream>
using namespace std;

class Student {
private:
int rollNo;
float marks;

public:
void setData(int r, float m); // Declared inside

void display() { // Defined inside (inline)
cout << "Roll No: " << rollNo << endl;
cout << "Marks: " << marks << endl;
}
};

// Defined outside using scope resolution operator
void Student::setData(int r, float m) {
rollNo = r;
marks = m;
}

int main() {
Student s1;
s1.setData(101, 95.5);
s1.display();
return 0;
}

🔷 Key Points

  1. Access: Member functions can directly access both private and public data members.
  2. Scope Resolution Operator ::: Used to define functions outside the class.
  3. Encapsulation: Functions operate on the data, ensuring safe access and modification.

🔷 Benefits of Using Member Functions

  • Maintains code reusability.
  • Promotes data abstraction and modularity.
  • Functions are tied to the class they operate on — this improves organization and readability.

🔷 Diagram (Text Format)

Class: Student
-----------------------------
| - rollNo : int |
| - marks : float |
| + setData(int, float) | --> defined outside
| + display() | --> defined inside
-----------------------------

Object: s1
s1.setData(101, 95.5)
s1.display()

🔷 Summary

  • Member functions define how an object behaves.
  • They can be defined inside (inline) or outside (with ::) the class.
  • They improve encapsulation, data protection, and object-oriented structure.