Methods
Anonymous contributor
Published Oct 12, 2021Updated Nov 28, 2024
Contribute to Docs
C++ class methods are functions defined within a class, accessed via dot notation (.
), and used to manipulate class members and behaviour.
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 methodstring 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() {cout << name << endl;}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;}string 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 contributor
- Christine_Yang
- garanews
- Anonymous contributor
- Anonymous contributor
- KyraThompson
Contribute to Docs
- 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.
Learn C++ on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Free course
Learn C++
Learn C++ — a versatile programming language that’s important for developing software, games, databases, and more.Beginner Friendly11 hours