2. Core member functions #
Created Sunday 29 November 2020
- Member functions of a class can be defined in two ways:
- Inside the class - this makes them inline, even if you don’t use the keyword.
class Box {
public:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
double getVolume(void) {
return length * breadth * height;
}
};
- Outside the class - they are normal functions. The full name of the functions must be provided, using the scope resolution operator(::).
class Box {
public:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};
double Box::getVolume(void) {
return length * breadth * height;
}
In C++, a class generally consists of two files:
.h
file - contains headers.cpp
file - contains definitions
Why use two(or multiple) files #
There are many reasons:
- ODR rule - C++ demands all entities be declared only once.
- Big programs compile faster, i.e compile only the files that have changed.
- Version control and collaboration is easy.
- Headers can be used as public facing API, i.e
.cpp
is obfuscated in proprietary software.