TDDE18 2020-11-03
#include <vector>
std::vector<int> v {5, 3, 1, 2};
v.at(1) = 4; // OR
v[1] = 4 // seg. fault possible
// (index start at 0)
v.push_back(3);
v.back() = 6;
v.pop_back();
v.front()
v.size()
vector<string> words {...};
// Following instruction are near equivalent
// use last one
for(int i{0}; i < words.size(); ++i)
for(string word : words)
for(string const& word : words)
{
cout << words.at(i) << endl;
}
class Base {
public:
//...
protected:
// Only accessible by the "family"
};
class Derived : public Base {
public:
Derived(int dev) : Base{}, init{dev}
{}
//...
private:
//...
};
class Shape{
public:
//...
virtual double area() const
{
return 0;
}
//...
};
class Rectangle : public Shape{
public:
//...
double area()const{
return width * height;
}
//...
};
int main () {
Rectangle r {10, 15};
cout << print_area(r) << endl; //prints150
}
Shape s{};
Rectangle r{10, 15};
Triangle t{3, 4};
Shape* ptr {&s};
ptr->area(); //returns 0
ptr = &r;
ptr->area(); //returns 150
ptr = &t;
ptr->area(); //returns 6
Always use pointers or references when dealing with polymorphic objects!
Sometimes, we have to make the destructor virtual:
class Shape{
public:
//...
virtual ~Shape() = default;
//...
};
Always declare the destructor of a polymorphic base class as virtual!
When a function must override another, we can add override
term to force the compiler to check that we actually override a function:
double area() const override {}
To force a function to be override in the parent function, we can use:
// Pure virtual function
virtual double area() const = 0;