Home >>Cpp Programs >Define a class method outside the class definition in C++
In this example, we will see a C++ program in which we will define a class method outside the class.
In this program, we will have three methods print1(), print2(), and printValue() which will be declared inside the class definitions and methods will be defined outside the class definition using the Scope Resolution Operator (::).
Program:
#include <iostream>
using namespace std;
// class definition
// "Sample" is a class
class Sample {
public: // Access specifier
// method declarations
void print1();
void print2();
void printValue(int value);
};
// Method definitions outside the class
// method definition 1
void Sample::print1()
{
cout << "Abhimanyu\n";
}
// method definition 2
void Sample::print2()
{
cout << "Jerry\n";
}
// method definition 3
// it will accept value while calling and print it
void Sample::printValue(int value)
{
cout << "value is: " << value << "\n";
}
int main()
{
// creating object
Sample obj;
// calling methods
obj.print1();
obj.print2();
obj.printValue(101);
return 0;
}