Home


Lesson 9

Operators overloading and memory management

Task 0: operator overloading

Create a class Country with a field: int population. Make operator++ increasing country's population:


// Testing
Contry c(1000000);
c++;
std::cout << "1000001 = " << c.get_population() << std::endl;
++c;
std::cout << "1000002 = " << c.get_population() << std::endl;
        

// Tip
class T
{
    public:
        
        // ++A
        T& operator++()
        {
            // todo
            return *this;
        }

        // A++
        T operator++(int)
        {
           ++(*this);
           return *this;
        }
};
                
Task 1: toString() like

Add a new field for class Country: string name. Override ostream::operator<<.


class A {
public:
    int i;
};
    
std::ostream& operator<<(std::ostream &strm, const A &a) {
    return strm << "A(" << a.i << ")";
}
                
Task 2

Create a student group class, where students could be assign to many groups at the same time. Create a field represents collection of students.

Task 3

Create a student class, which contains a collection of groups the student belongs.

Task 4

Create a student destructor, that will destroy all groups, which contain no students anymore.