C++ Notes
Published:
I have largely evaded formally learning C++ by leveraging my knowledge of C to pattern match on existing C++ codebases, or using Rust in my own green-field projects. Nevertheless, it seems that knowing C++ is pretty important given that everyone still uses it and test on its concepts in interviews. I guess I cannot possibly continue on without knowing what a virtual method call is.
A previous company shipped me a copy of “A Tour of C++, Third Edition” by Bjarne Stroustrup. I’ll be dumping my notes here so I actually remember stuff.
class Vector {
public:
Vector(int s) :elem{new double[s]}, sz{s} {}
double& operator[](int i) { return elem[i]; }
int size() { return sz; }
private:
double* elem;
int sz;
};
int main() {
Vector v(6);
}
enum class Color { red, green, blue };
export module vector_printer;
import std;
export template<typename T> void print(std::vector<T>& v)
{
cout << "{\n";
for (const T& val : v) {
std::cout << " " << val << '\n';
}
cout << "}\n";
}
polymorphism
using namespace std;
class base {
public:
virtual void print() { cout << "print base class\n"; }
void show() { cout << "show base class\n"; }
};
class derived : public base {
public:
void print() { cout << "print derived class\n"; }
void show() { cout << "show derived class\n"; }
};
int main()
{
base* bptr;
derived d;
bptr = &d;
// Virtual function, binded at runtime
bptr->print();
// Non-virtual function, binded at compile time
bptr->show();
return 0;
}
% Output
print derived class
show base class
Basically when you declare a class’s method as virtual, you are ensuring that sub-classes use their own implementation. Aka, override-able functions.