Methods
Anonymous contributor
Anonymous contributor1 total contribution
Anonymous contributor
Published Oct 12, 2021Updated Jul 20, 2023
Contribute to Docs
C++ class methods are user-defined functions that can be used within an instance of the class. A dot notation .
is used 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 methodvoid get_name() {return name;}}int main() {Person robert;// Calls the methodrobert.get_name();return 0;}
Outside the Class
class Person {string name;public:void get_name();}// Defines the methodvoid Person::get_name() {return name;}int main() {Person robert;// Calls the methodrobert.get_name();return 0;}
Parameters can also be added to class methods:
class Person {string name;public:// Defines the methodvoid set_name(string newName) {name = newName;}void get_name() {return name;}}int main() {Person robert;// Sets the name class memberrobert.set_name("Robert");// Prints "Robert"std::cout << robert.get_name();return 0;}
All contributors
- Anonymous contributorAnonymous contributor1 total contribution
- Christine_Yang265 total contributions
- garanews209 total contributions
- Anonymous contributorAnonymous contributor3077 total contributions
- Anonymous contributor
- Christine_Yang
- garanews
- Anonymous contributor
Looking to contribute?
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.