C++ Class Methods
In this page:
What is a Class Method?
A class method, also called a member function, is a function declared as part of a class, and every object of that class can call it, giving the method automatic access to that specific object's data.
Example: What is a Class Method?
#include <iostream>
class Greeter {
public:
void greet() { std::cout << "Hello!" << std::endl; }
};
int main() {
Greeter g;
g.greet();
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Defining a Method Inline
A method's body can be written directly inside the class definition, called an inline definition, which is convenient for short methods but keeps the class declaration longer.
Example: Defining a Method Inline
#include <iostream>
class Box {
public:
int getSize() { return 10; } // defined inline, right inside the class
};
int main() {
Box b;
std::cout << b.getSize() << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Defining a Method Outside the Class
A method can be declared inside the class but defined later outside it, using the class name followed by :: (the scope resolution operator) to indicate which class the definition belongs to.
Example: Defining a Method Outside the Class
#include <iostream>
class Box {
public:
int getSize();
};
int Box::getSize() {
return 20;
}
int main() {
Box b;
std::cout << b.getSize() << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Methods that Return a Value
A method can return a value just like a regular function, computed from the calling object's own member variables, letting the object provide information about its own state.
Example: Methods that Return a Value
#include <iostream>
class Circle {
double radius = 2.0;
public:
double area() { return 3.14159 * radius * radius; }
};
int main() {
Circle c;
std::cout << c.area() << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Methods that Take Parameters
A method can accept its own parameters in addition to having access to the object's member variables, letting it combine external input with the object's internal state.
Example: Methods that Take Parameters
#include <iostream>
class Calculator {
public:
int add(int a, int b) { return a + b; }
};
int main() {
Calculator calc;
std::cout << calc.add(3, 4) << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 14 topics to unlock
0/14 topics done
Complete these topics first: