Declaration and definition

Declaration

Class and and its member functions can be split into declaration and definition. The declaration part is:

class MyClass{
public:
    int x;
    void setX(int value);
    int getX();
};

Definition

The definition follows the type ClassName::functionName() signature:

void MyClass::setX(int value){
	x = value;
}

int MyClass::getX(){
	return x;
}

The full example is:

#include <iostream>
class MyClass{ // declaration
public:
    int x;
    void setX(int value);
    int getX();
};
// definition
void MyClass::setX(int value){
	x = value;
}

int MyClass::getX(){
	return x;
}

int main(){
	MyClass o;
	o.setX(123);
	std::cout << "X is: " << o.getX() << std::endl;
}

Usualy the declaration part of the class is stored in external file with the .h extension called header or header file. The definition part is stored in a file with the .cpp extension refered to as a source file.

Header file

The content of an external myclass.h header file:

#include <iostream>
class MyClass{
public:
    int x;
    void setX(int value);
    int getX();
};

Source file

The content of an external myclass.cpp source file:

#include "myclass.h"
#include <iostream>

void MyClass::setX(int value){
	x = value;
}

int MyClass::getX(){
	return x;
}

The main file

The content of a main main.cpp source file:

#include "myclass.h"
#include <iostream>

int main(){
	MyClass o;
	o.setX(123);
	std::cout << "X is: " << o.getX() << std::endl;
}