Ready to practice?
Sign up to access interactive coding exercises and track your progress.
Adding Behavior to Classes
Define functions inside classes that operate on member data using the implicit this pointer.
Member Functions
Member functions are functions defined inside a class. They provide behaviors for objects of that class.
Basic member functions
class Score
{
public:
int points{};
void addPoints(int amount)
{
points += amount;
}
void reset()
{
points = 0;
}
int getPoints()
{
return points;
}
};
Each member function operates on the object it's called through. When you call score.addPoints(10), the function modifies score's points member.
Implicit object parameter
Member functions have access to a hidden parameter: a pointer to the object they're called on. Though invisible in the function signature, this mechanism allows member functions to access the calling object's data.
#include <iostream>
class Damage
{
public:
int base{};
int withCritical()
{
return base * 2;
}
void show()
{
std::cout << "Base: " << base << ", Critical: " << withCritical() << '\n';
}
};
int main()
{
Damage attack{ 50 };
attack.show(); // Base: 50, Critical: 100
return 0;
}
When show() calls withCritical(), both functions operate on the same attack object.
Defining member functions outside the class
For longer functions, you can declare them inside the class but define them outside:
class Player
{
public:
int health{};
int maxHealth{};
void heal(int amount);
void takeDamage(int amount);
void showStatus();
};
void Player::heal(int amount)
{
health += amount;
if (health > maxHealth)
health = maxHealth;
}
void Player::takeDamage(int amount)
{
health -= amount;
if (health < 0)
health = 0;
}
void Player::showStatus()
{
std::cout << "Health: " << health << "/" << maxHealth << '\n';
}
Use the scope resolution operator (::) to indicate which class the function belongs to.
Member functions calling other member functions
Member functions can call other member functions of the same class:
class Inventory
{
public:
int slots{};
int usedSlots{};
bool hasFreeSlot()
{
return usedSlots < slots;
}
bool addItem()
{
if (hasFreeSlot())
{
++usedSlots;
return true;
}
return false;
}
int getFreeSlots()
{
return slots - usedSlots;
}
};
The addItem() function calls hasFreeSlot() to check availability before adding an item.
Member functions vs. free functions
Consider displaying a weapon's information. You could write a free function:
void displayWeapon(const Weapon& wpn)
{
std::cout << wpn.name << ": " << wpn.damage << " damage\n";
}
// Usage
displayWeapon(sword);
Or a member function:
class Weapon
{
public:
std::string name{};
int damage{};
void display()
{
std::cout << name << ": " << damage << " damage\n";
}
};
// Usage
sword.display();
Member functions are preferred when:
- The function logically belongs to the object
- The function needs access to private members
- You want a clear association between the object and the action
Free functions are better when:
- The function works with multiple unrelated types
- The function doesn't need special access to the class
- You want to keep the class interface minimal
Best practices
Keep member functions focused: Each function should do one thing well.
class Wallet
{
public:
int gold{};
void addGold(int amount) // Does one thing
{
gold += amount;
}
bool spendGold(int amount) // Does one thing
{
if (amount <= gold)
{
gold -= amount;
return true;
}
return false;
}
};
Use const for functions that don't modify the object: (We'll cover this in the next lesson)
Name functions clearly: Use verbs for actions (calculate, update, display) and nouns/adjectives for queries (getLevel, isEmpty, isAlive).
Core Understanding
Member functions provide behaviors for class objects, operating on the object's data and calling other member functions as needed.
Summary
Member functions are functions defined inside a class that provide behaviors for objects of that class, operating on the object's member variables.
Implicit object parameter is a hidden mechanism that gives member functions access to the object they're called on, allowing them to work with that specific object's data.
Calling member functions uses dot notation (object.function()), with the function operating on the data belonging to that specific object.
Defining outside the class separates declaration (in the class) from definition (outside), using the scope resolution operator (::) to indicate which class the function belongs to.
Member functions calling others is common and natural—member functions can call other member functions of the same class, all operating on the same object.
Member functions vs free functions involves choosing whether functionality belongs as part of the object's interface or as separate utilities. Member functions are preferred when the function logically belongs to the object or needs access to private members.
Best practices include keeping functions focused on single responsibilities, using const for non-modifying functions, and naming functions clearly with verbs for actions and nouns/adjectives for queries.
Free functions are better when working with multiple unrelated types, not needing special class access, or wanting to keep the class interface minimal.
Member functions enable object-oriented design by bundling behaviors with data, creating cohesive units that model real-world concepts intuitively and maintain their own state and operations.
Adding Behavior to Classes - Quiz
Test your understanding of the lesson.
Practice Exercises
Member Functions
Practice creating classes with member functions.
Lesson Discussion
Share your thoughts and questions
No comments yet. Be the first to share your thoughts!