archer2-cpp
The course deals with C++ concepts for scientific computing including classes, vectors etc.
Struct
struct is a type of class in C++ which is a custom variable defined as a set of other variables.
struct Complex{
double re;
double im;
};Struct with no default values can be initialized in-line.
Complex make_unit_complex(){
return Complex(0.0,1.0);
}Setting the default value for the components of the struct will make them lose the ability to be initialized in-line.
struct Complex2 {
double re = 0.0;
double im = 0.0;
};
// This will not work
Complex2 make_unit_complex2(){
return Complex2(0,1);
}For this purpose, you can use constructors, which are functions used to initialize structs.
#include <cassert>
#include <iostream>
struct complex3 {
complex3() = default; //default initialiser uses explicit values
complex3(double re); //Purely real initializer
complex3(double re, double im); //complex3 initializer
double re = 0.0; //explicit defaults when nothing is used
double im = 0.0;
};
//define purely real constructor
complex3::complex3(double real) : re(real) {}
//define complex3 constructor
complex3::complex3(double real, double imag) : re(real), im(imag) {}
void test() {
auto Z = complex3(0,1);
assert(Z.re == 0);
assert(Z.im == 1);
auto Y = complex3();
assert(Y.re == 0);
assert(Y.im == 0);
auto X = complex3(1.0);
assert(X.re == 1);
assert(X.im == 0);
complex3 pi = 3.1459; // pi.im = 0
assert(pi.re == 3.1459);
assert(pi.im == 0);
}
int main(int argc, char *arv[]) {
test();
std::cout << "The tests were passed!" << std::endl;
return 0;
}Object Oriented Programming
Objects are elements of code that can data and code. An object’s procedures
i.e. member functions can access and modify the data in the objects. For
example, name.size() is a member function of the string std::string name
that returns its size.