C++ Member Functions

🧠 C++ Member Functions – Let Objects Do Things

In C++, member functions are like the skills or actions of a class. They live inside the class and tell the object what it can do. 🎮

📦 What is a Member Function?

A member function is a function that belongs to a class. You call it using an object, like this:

objectName.functionName();

🔧 Example: Using Member Functions

#include <iostream>
using namespace std;

class Dog {
public:
    string name;

    void bark() {
        cout << name << " says Woof! 🐶" << endl;
    }
};

int main() {
    Dog myDog;
    myDog.name = "Buddy";
    myDog.bark();  // Calling the member function

    return 0;
}
  

Try It Now

🚪 Inside vs Outside Definition

You can define a member function inside the class or outside using :: (scope resolution operator).

📍 Defining Outside the Class

#include <iostream>
using namespace std;

class Cat {
public:
    void meow();  // Just a declaration
};

// Definition outside the class
void Cat::meow() {
    cout << "Meow from outside! 🐱" << endl;
}

int main() {
    Cat kitty;
    kitty.meow();

    return 0;
}
  

Try It Now

🧾 Member Function Tips

  • Defined inside class = inline by default
  • Use ClassName::FunctionName for outside definitions
  • You can use member functions to access private members

🧠 Summary

  • Member functions belong to a class
  • They describe what an object can do
  • You can define them inside or outside the class

Now your C++ objects are not just data—they can act, bark, meow, and do things! 🦴🎯