Methods

Methods

C++ class methods are user-defined functions that can be used within an instance of the class. We use a dot notation . before method names to distinguish them from regular functions.

Class Methods

A class method can be defined in two ways:

  • Inside the class definition
  • Outside the class definition

Inside the Class

class Person {
string name;
public:
// Defines the method
void get_name() {
return name;
}
}
int main() {
Person robert;
// Calls the method
robert.get_name();
return 0;
}

Outside the Class

class Person {
string name;
public:
void get_name();
}
// Defines the method
void Person::get_name() {
return name;
}
int main() {
Person robert;
// Calls the method
robert.get_name();
return 0;
}

Parameters can also be added to class methods:

class Person{
string name;
public:
// Defines the method
void set_name(string newName){
name = newName;
}
void get_name() {
return name;
}
}
int main() {
Person robert;
// Sets the name class memeber
robert.set_name("Robert");
// Prints "Robert"
std::cout << robert.get_name();
return 0;
}
Edit this page on GitHub

Contributors

Interested in helping build Docs? Read the Contribution Guide or share your feedback.

Learn C++ on Codecademy

Edit this page on GitHub

Contributors