C++ Class Methods

🧩 C++ Class Methods (Member Functions)

Class methods (also called member functions) are functions that belong to a class and define the behavior of objects created from that class.


πŸ”Ή 1. What Are Class Methods?

  • Functions declared inside a class

  • Operate on the data members of the class

  • Called using objects or object pointers


πŸ”Ή 2. Method Defined Inside the Class

class Student {
public:
int id;
string name;
void display() {
cout << id << ” “ << name << endl;
}
};

Usage:

Student s;
s.id = 101;
s.name = "Sanjit";
s.display();

πŸ”Ή 3. Method Defined Outside the Class

class Student {
public:
int id;
string name;
void display(); // declaration
};

void Student::display() { // definition
cout << id << ” “ << name << endl;
}

βœ” Cleaner
βœ” Better for large programs


πŸ”Ή 4. Public vs Private Methods

class Account {
private:
int balance;
void showSecret() {
cout << “Secret”;
}

public:
void setBalance(int b) {
balance = b;
}

int getBalance() {
return balance;
}
};


πŸ”Ή 5. Methods with Parameters

class Calculator {
public:
int add(int a, int b) {
return a + b;
}
};

πŸ”Ή 6. Methods with Return Value

class Box {
public:
int volume(int l, int w, int h) {
return l * w * h;
}
};

πŸ”Ή 7. this Pointer in Methods

Used when data member and parameter have same name.

class Demo {
public:
int x;
void set(int x) {
this->x = x;
}
};


πŸ”Ή 8. const Methods

A const method cannot modify object data.

class Student {
public:
int id;
int getId() const {
return id;
}
};

βœ” Ensures safety
βœ” Used for getters


πŸ”Ή 9. Static Class Methods

Belong to the class, not to objects.

class Math {
public:
static int square(int x) {
return x * x;
}
};

Call:

cout << Math::square(5);

πŸ”Ή 10. Inline Class Methods

Methods defined inside class are inline by default.

class Test {
public:
void show() {
cout << "Inline method";
}
};

πŸ”Ή 11. Method Overloading

class Print {
public:
void show(int x) {
cout << x;
}
void show(string s) {
cout << s;
}
};


πŸ”Ή 12. Method with Object as Parameter

class Box {
public:
int length;
void copy(Box b) {
length = b.length;
}
};


❌ Common Mistakes

void display(); // ❌ not a class method if outside class

βœ” Correct:

void Student::display();

πŸ“Œ Summary

  • Class methods define object behavior

  • Can be inside or outside class

  • Use this to avoid name conflicts

  • const methods protect data

  • Static methods belong to class

  • Support overloading

You may also like...