Lesson 10-C++ Class Initialization, Assignment, and Destruction

Class Initialization

Constructor Initialization List

The constructor initialization list starts with a colon, followed by a comma-separated list of data members, each followed by an initializer in parentheses. The initialization order of member variables follows their declaration order in the class, not the order in the initialization list.

Example Code Suppose we have a simple class Point with two private member variables x and y, and a constructor to initialize these two member variables.

#include <iostream>

class Point {
public:
    // Constructor
    Point(int x, int y) : x_(x), y_(y) {
        std::cout << "Point initialized with x=" << x_ << " and y=" << y_ << std::endl;
    }

private:
    int x_; // Private member variable
    int y_; // Private member variable
};

int main() {
    Point p(10, 20); // Call constructor and initialize member variables
    return 0;
}

In this example, the constructor of the Point class uses an initialization list to set the values of x_ and y_. The constructor is defined as follows:

Point(int x, int y) : x_(x), y_(y) {
    std::cout << "Point initialized with x=" << x_ << " and y=" << y_ << std::endl;
}

Here, x_(x) and y_(y) indicate that x_ and y_ are initialized to the values of the passed parameters x and y, respectively.

Importance of Initialization List Using an initialization list to initialize member variables has several benefits:

  • Efficiency: Member variables can be assigned directly without going through assignment operations in the constructor body.
  • Safety: Ensures that member variables are properly initialized before the constructor body executes, which is particularly important for certain types (such as pointers or resource handles).
  • Support for Value Types: For certain types (such as built-in types or class types), the initialization list provides a more efficient initialization method.
  • Support for References and Constant Members: For reference or constant members, the initialization list must be used for initialization.

Example Code

Here is a more complex example showing a class with different types of member variables and how to use an initialization list to initialize these members.

#include <iostream>
#include <string>

class ComplexClass {
public:
    // Constructor
    ComplexClass(int id, const std::string& name, double value)
        : id_(id), name_(name), value_(value) {
        std::cout << "ComplexClass initialized with id=" << id_
                  << ", name=" << name_ << ", value=" << value_ << std::endl;
    }

private:
    int id_;          // Integer member variable
    std::string name_; // String member variable
    double value_;    // Floating-point member variable
};

int main() {
    ComplexClass obj(1, "Example", 3.14);
    return 0;
}

In this example, ComplexClass contains three member variables of different types: int, std::string, and double. The constructor uses an initialization list to initialize these member variables.

Class Constructors

Basic Form of Constructors

The name of the constructor is the same as the class name and has no return type. Constructors can have parameters or none.

Syntax

class ClassName {
public:
    ClassName() { /* Initialization logic */ }
    ClassName(ParamType param) { /* Initialization logic */ }
};

Default Constructor

The default constructor is a constructor with no parameters. If no constructor is provided, the compiler will generate a default constructor automatically.

#include <iostream>

class Point {
public:
    Point() {
        x = 0;
        y = 0;
        std::cout << "Default constructor called." << std::endl;
    }

private:
    int x;
    int y;
};

int main() {
    Point p; // Call default constructor
    return 0;
}

Parameterized Constructor

A parameterized constructor accepts one or more parameters and uses these parameters to initialize the object’s member variables.

#include <iostream>

class Point {
public:
    Point(int x, int y) : x_(x), y_(y) {
        std::cout << "Parameterized constructor called." << std::endl;
    }

private:
    int x_;
    int y_;
};

int main() {
    Point p(10, 20); // Call parameterized constructor
    return 0;
}

Initialization List

The initialization list is a more efficient way to initialize member variables. It starts with a colon in the constructor definition, followed by a series of initialization items.

#include <iostream>

class Point {
public:
    Point(int x, int y) : x_(x), y_(y) {
        std::cout << "Initialized with x=" << x_ << " and y=" << y_ << std::endl;
    }

private:
    int x_;
    int y_;
};

int main() {
    Point p(10, 20);
    return 0;
}

Initialization of Complex Types

For complex type member variables, such as strings, arrays, etc., the initialization list can be used for initialization.

#include <iostream>
#include <string>

class Person {
public:
    Person(const std::string& name, int age)
        : name_(name), age_(age) {
        std::cout << "Person initialized with name=" << name_ << " and age=" << age_ << std::endl;
    }

private:
    std::string name_;
    int age_;
};

int main() {
    Person p("Alice", 30);
    return 0;
}

Constructor Overloading

Multiple constructors can be defined as long as their parameter lists are different. This is called constructor overloading.

#include <iostream>

class Point {
public:
    Point() : x_(0), y_(0) {
        std::cout << "Default constructor called." << std::endl;
    }

    Point(int x, int y) : x_(x), y_(y) {
        std::cout << "Parameterized constructor called." << std::endl;
    }

private:
    int x_;
    int y_;
};

int main() {
    Point p1; // Call default constructor
    Point p2(10, 20); // Call parameterized constructor
    return 0;
}

Complex Example: Containing Different Types of Member Variables

The following example shows how to use different types of member variables in a class at the same time and use the initialization list to initialize them.

#include <iostream>
#include <string>

class ComplexClass {
public:
    ComplexClass(int id, const std::string& name, double value)
        : id_(id), name_(name), value_(value) {
        std::cout << "ComplexClass initialized with id=" << id_
                  << ", name=" << name_ << ", value=" << value_ << std::endl;
    }

private:
    int id_;          // Integer member variable
    std::string name_; // String member variable
    double value_;    // Floating-point member variable
};

int main() {
    ComplexClass obj(1, "Example", 3.14);
    return 0;
}

Constructor Call Order

If a class inherits from another class and includes a call to the base class constructor, the base class constructor will be called before the derived class constructor.

#include <iostream>

class Base {
public:
    Base(int x) : x_(x) {
        std::cout << "Base constructor called with x=" << x_ << std::endl;
    }

private:
    int x_;
};

class Derived : public Base {
public:
    Derived(int x, int y) : Base(x), y_(y) {
        std::cout << "Derived constructor called with y=" << y_ << std::endl;
    }

private:
    int y_;
};

int main() {
    Derived d(10, 20);
    return 0;
}

Class Destructors

Basic Form of Destructors

The name of the destructor is the same as the class name but prefixed with a tilde ~. The destructor has no return type and accepts no parameters.

Syntax

class ClassName {
public:
    ~ClassName() {
        // Code to clean up resources
    }
};

Characteristics of Destructors

  • Automatic Call: The destructor is automatically called when the object goes out of scope or is explicitly deleted.
  • Single Destructor: Each class can have only one destructor.
  • No Parameters: The destructor accepts no parameters.
  • No Return Type: The destructor has no return type, not even void.

Uses of Destructors

The destructor is mainly used to release resources occupied by the object, such as dynamically allocated memory, file handles, etc.

Destructor Call Timing

The destructor is automatically called in the following situations:

  • When the object goes out of scope (e.g., at the end of a function).
  • When the object is explicitly deleted using the delete operator.
  • When the program ends, global and static objects are destroyed.
#include <iostream>

class MyClass {
public:
    ~MyClass() {
        std::cout << "Destructor called." << std::endl;
    }
};

int main() {
    MyClass obj; // Object created
    return 0; // Destructor called when obj goes out of scope
}

Destructor and Resource Management

The destructor is an ideal place to release resources. For example, if the class dynamically allocates memory in the constructor, it should be released in the destructor.

#include <iostream>

class ResourceManager {
public:
    ResourceManager() {
        resource = new int(42);
        std::cout << "Resource allocated." << std::endl;
    }

    ~ResourceManager() {
        delete resource;
        std::cout << "Resource released." << std::endl;
    }

private:
    int* resource;
};

int main() {
    ResourceManager rm; // Resource allocated
    return 0; // Resource released
}

Virtual Destructor

If the class is intended to be used as a base class, the destructor should be declared as virtual to ensure that the destructor of the derived class is called correctly when deleting through a base class pointer.

#include <iostream>

class Base {
public:
    virtual ~Base() {
        std::cout << "Base destructor." << std::endl;
    }
};

class Derived : public Base {
public:
    ~Derived() {
        std::cout << "Derived destructor." << std::endl;
    }
};

int main() {
    Base* b = new Derived();
    delete b; // Calls Derived destructor then Base destructor
    return 0;
}

Example Code

Here is an example code demonstrating the use of a destructor:

#include <iostream>

class DestructorExample {
public:
    DestructorExample() {
        std::cout << "Constructor called." << std::endl;
    }

    ~DestructorExample() {
        std::cout << "Destructor called." << std::endl;
    }
};

int main() {
    DestructorExample obj; // Constructor called
    return 0; // Destructor called
}

Assignment Operators

Assignment Operator Definition

The assignment operator is a special member function used to assign the value of one object to another object of the same type. The default assignment operator performs a shallow copy.

Assignment Operator Syntax

The assignment operator is overloaded as a member function with the signature ClassName& operator=(const ClassName& other).

class MyClass {
public:
    MyClass& operator=(const MyClass& other) { // Assignment operator
        if (this != &other) {
            // Copy logic
        }
        return *this;
    }
};

Default Assignment Operator

If no assignment operator is defined, the compiler generates a default one that performs member-wise copy.

class MyClass {
public:
    int x;
};

int main() {
    MyClass obj1;
    obj1.x = 42;
    MyClass obj2 = obj1; // Default assignment operator
    return 0;
}

Custom Assignment Operator

A custom assignment operator allows defining specific copy behavior, especially for classes with dynamic memory.

#include <cstring>

class String {
public:
    String(const char* str) {
        data = new char[strlen(str) + 1];
        strcpy(data, str);
    }

    String& operator=(const String& other) { // Custom assignment operator
        if (this != &other) {
            delete[] data;
            data = new char[strlen(other.data) + 1];
            strcpy(data, other.data);
        }
        return *this;
    }

    ~String() {
        delete[] data;
    }

private:
    char* data;
};

Move Assignment Operator

The move assignment operator transfers resources from an rvalue reference, avoiding unnecessary copies.

class MyClass {
public:
    MyClass& operator=(MyClass&& other) noexcept { // Move assignment operator
        if (this != &other) {
            // Move logic
        }
        return *this;
    }
};

Example Code

Here is an example code demonstrating the assignment operator:

#include <iostream>

class AssignExample {
public:
    AssignExample(int value) : val(value) {}

    AssignExample& operator=(const AssignExample& other) {
        if (this != &other) {
            val = other.val;
        }
        return *this;
    }

    void print() const {
        std::cout << "Value: " << val << std::endl;
    }

private:
    int val;
};

int main() {
    AssignExample obj1(42);
    AssignExample obj2(0);
    obj2 = obj1; // Assignment operator called
    obj2.print(); // Output: Value: 42
    return 0;
}

Class Object Pointers

Pointer to Class Object

A pointer to a class object is a pointer variable that points to an object of a class. It can be used to dynamically allocate and manage class objects.

#include <iostream>

class MyClass {
public:
    void print() const {
        std::cout << "Hello from MyClass!" << std::endl;
    }
};

int main() {
    MyClass* ptr = new MyClass(); // Pointer to class object
    ptr->print(); // Call member function through pointer
    delete ptr; // Release memory
    return 0;
}

Pointer to Member Variable

A pointer to a member variable is a pointer that points to a non-static member variable of a class. It needs to be used in conjunction with an object pointer or reference.

#include <iostream>

class MyClass {
public:
    int x;
};

int main() {
    MyClass obj;
    int MyClass::*px = &MyClass::x; // Pointer to member variable
    obj.*px = 10; // Assign value through pointer
    std::cout << "Value of x: " << obj.x << std::endl; // Output: Value of x: 10
    return 0;
}

Pointer to Member Function

A pointer to a member function is a pointer that points to a non-static member function of a class. It needs to be used in conjunction with an object pointer or reference.

#include <iostream>

class MyClass {
public:
    void print() const {
        std::cout << "Hello from MyClass!" << std::endl;
    }
};

int main() {
    MyClass obj;
    void (MyClass::*ptr)() const = &MyClass::print; // Pointer to member function
    (obj.*ptr)(); // Call member function through pointer
    return 0;
}

Pointer to Static Member Variable

A pointer to a static member variable is a pointer that points to a static member variable of a class. Since static members do not belong to any specific object, they can be accessed directly through the class name.

#include <iostream>

class MyClass {
public:
    static int staticVar;
};

int MyClass::staticVar = 42; // Initialization of static member variable

int main() {
    int* ptr = &MyClass::staticVar; // Pointer to static member variable
    std::cout << "Value of staticVar: " << *ptr << std::endl; // Output: Value of staticVar: 42
    return 0;
}

Pointer to Static Member Function

A pointer to a static member function is a pointer that points to a static member function of a class. Since static member functions do not belong to any specific object, they can be called directly through the class name.

#include <iostream>

class MyClass {
public:
    static void staticPrint() {
        std::cout << "Hello from static member function!" << std::endl;
    }
};

int main() {
    void (*ptr)() = &MyClass::staticPrint; // Pointer to static member function
    ptr(); // Call static member function through pointer
    return 0;
}

Example Code

Here is an example code demonstrating the use of class object pointers:

#include <iostream>

class PointerExample {
public:
    void print() const {
        std::cout << "Hello from PointerExample!" << std::endl;
    }
};

int main() {
    PointerExample* ptr = new PointerExample(); // Pointer to class object
    ptr->print(); // Call member function through pointer
    delete ptr; // Release memory
    return 0;
}

Class Object Arrays

Class Object Arrays

A class object array is an array composed of class objects. Each element in the array is an object of the class.

#include <iostream>

class MyClass {
public:
    MyClass(int id) : id_(id) {
        std::cout << "MyClass constructed with id=" << id_ << std::endl;
    }

    ~MyClass() {
        std::cout << "MyClass destructed with id=" << id_ << std::endl;
    }

private:
    int id_;
};

int main() {
    MyClass arr[3] = {MyClass(1), MyClass(2), MyClass(3)}; // Class object array

    return 0;
}

Dynamic Allocation of Class Object Arrays

Dynamically allocated class object arrays can be created using the new operator and released using the delete[] operator.

#include <iostream>

class MyClass {
public:
    MyClass(int id) : id_(id) {
        std::cout << "MyClass constructed with id=" << id_ << std::endl;
    }

    ~MyClass() {
        std::cout << "MyClass destructed with id=" << id_ << std::endl;
    }

private:
    int id_;
};

int main() {
    MyClass* arr = new MyClass[3]{{1}, {2}, {3}}; // Dynamically allocate class object array

    delete[] arr; // Release array

    return 0;
}

Accessing Class Object Arrays

Elements in a class object array can be accessed using subscripts or pointers.

#include <iostream>

class MyClass {
public:
    MyClass(int id) : id_(id) {}

    int getId() const {
        return id_;
    }

private:
    int id_;
};

int main() {
    MyClass arr[3] = {MyClass(1), MyClass(2), MyClass(3)};

    for (int i = 0; i < 3; ++i) {
        std::cout << "Accessing MyClass object with id=" << arr[i].getId() << std::endl;
    }

    return 0;
}

Using std::vector to Store Class Objects

std::vector is a dynamic array that can store class objects and provides more flexibility than fixed-size arrays.

#include <iostream>
#include <vector>

class MyClass {
public:
    MyClass(int id) : id_(id) {
        std::cout << "MyClass constructed with id=" << id_ << std::endl;
    }

    ~MyClass() {
        std::cout << "MyClass destructed with id=" << id_ << std::endl;
    }

    int getId() const {
        return id_;
    }

private:
    int id_;
};

int main() {
    std::vector<MyClass> myVector;

    // Add elements
    myVector.push_back(MyClass(1));
    myVector.push_back(MyClass(2));
    myVector.push_back(MyClass(3));

    // Access elements
    for (size_t i = 0; i < myVector.size(); ++i) {
        std::cout << "Accessing MyClass object with id=" << myVector[i].getId() << std::endl;
    }

    // Delete element
    myVector.pop_back();

    return 0;
}

Difference Between Class Object Arrays and std::vector

  • Capacity: The capacity of an array is fixed at creation, while the capacity of std::vector can change at runtime.
  • Memory Management: Array memory is usually allocated on the stack, while std::vector memory is usually allocated on the heap.
  • Efficiency: Array access is more efficient because its memory is contiguous; std::vector may need to reallocate memory, so efficiency may be lower when inserting or deleting elements.
  • Dynamic Adjustment: std::vector supports dynamic size adjustment, while arrays do not.

Using std::vector for Dynamic Adjustment

std::vector provides multiple methods for dynamic size adjustment, such as push_back, pop_back, resize, etc.

Example Code

#include <iostream>
#include <vector>

class MyClass {
public:
    MyClass(int id) : id_(id) {
        std::cout << "MyClass constructed with id=" << id_ << std::endl;
    }

    ~MyClass() {
        std::cout << "MyClass destructed with id=" << id_ << std::endl;
    }

private:
    int id_;
};

int main() {
    std::vector<MyClass> myVector;

    // Dynamically add elements
    myVector.push_back(MyClass(1));
    myVector.push_back(MyClass(2));
    myVector.push_back(MyClass(3));

    // Dynamically adjust size
    myVector.resize(5); // Expand to 5 elements
    myVector.resize(2); // Shrink to 2 elements

    // Access elements
    for (size_t i = 0; i < myVector.size(); ++i) {
        std::cout << "Accessing MyClass object with id=" << myVector[i].getId() << std::endl;
    }

    return 0;
}

Performance Considerations

Although std::vector provides many convenient features, in performance-sensitive applications, note the following:

  • Memory Allocation: Frequent memory allocation and deallocation may lead to performance degradation.
  • Cache Locality: Since the memory of std::vector is usually contiguous, it can utilize cache locality well; std::vector may need to reallocate memory, which can lead to additional overhead.

Member Classes

Basic Form of Member Classes

The definition of a member class is similar to other classes, except that it is located within the definition of another class.

Syntax

class OuterClass {
public:
    class InnerClass {
    public:
        // Members of the inner class
    };
};

Accessing Members of the Outer Class

A member class can directly access all members of the outer class, including private members.

Example Code

#include <iostream>

class OuterClass {
public:
    int outerVar;

private:
    int privateOuterVar;

    class InnerClass {
    public:
        void accessPrivateMembers() {
            std::cout << "Accessing private member of OuterClass: " << privateOuterVar << std::endl;
        }
    };
};

int main() {
    OuterClass oc;
    oc.outerVar = 10;
    oc.privateOuterVar = 20;

    OuterClass::InnerClass ic;
    ic.accessPrivateMembers(); // Can access private members of the outer class

    return 0;
}

Creating Member Class Objects

Member class objects can be created through objects of the outer class or directly.

Example Code

#include <iostream>

class OuterClass {
public:
    class InnerClass {
    public:
        void print() {
            std::cout << "InnerClass object created." << std::endl;
        }
    };
};

int main() {
    OuterClass oc;
    OuterClass::InnerClass ic; // Directly create member class object
    ic.print();

    OuterClass::InnerClass ic2 = oc.InnerClass(); // Create member class object through outer class object
    ic2.print();

    return 0;
}

Member Classes and Scope of Outer Classes

Member classes can access all members of the outer class, but the outer class cannot directly access private members of the member class. If access to member class members from the outer class is needed, public interfaces can be defined.

Example Code

#include <iostream>

class OuterClass {
public:
    class InnerClass {
    public:
        void setInnerValue(int value) {
            innerValue = value;
        }

        int getInnerValue() const {
            return innerValue;
        }

    private:
        int innerValue;
    };

    void accessInnerValue() {
        InnerClass ic;
        ic.setInnerValue(100);
        std::cout << "Accessing inner value: " << ic.getInnerValue() << std::endl;
    }
};

int main() {
    OuterClass oc;
    oc.accessInnerValue();

    return 0;
}

Member Classes as Template Parameters

Member classes can be used as template parameters, allowing member classes to be part of generic types.

Example Code

#include <iostream>
#include <vector>

class OuterClass {
public:
    class InnerClass {
    public:
        void print() {
            std::cout << "InnerClass object created." << std::endl;
        }
    };
};

template<typename T>
void print(T t) {
    t.print();
}

int main() {
    OuterClass::InnerClass ic;
    print(ic);

    std::vector<OuterClass::InnerClass> vec;
    vec.push_back(ic);
    print(vec[0]);

    return 0;
}

Member Classes and Friends

Member classes can become friend classes of the outer class, allowing access to private members of the outer class.

#include <iostream>

class OuterClass {
public:
    int outerVar;

private:
    int privateOuterVar;

    friend class OuterClass::InnerClass; // Member class is a friend of the outer class

    class InnerClass {
    public:
        void accessPrivateMembers() {
            std::cout << "Accessing private member of OuterClass: " << privateOuterVar << std::endl;
        }
    };
};

int main() {
    OuterClass oc;
    oc.outerVar = 10;
    oc.privateOuterVar = 20;

    OuterClass::InnerClass ic;
    ic.accessPrivateMembers(); // Can access private members of the outer class

    return 0;
}

Member Classes and Inheritance

Member classes can inherit from other classes and still maintain their identity as members of the outer class.

Example Code

#include <iostream>

class BaseClass {
public:
    void print() {
        std::cout << "BaseClass object." << std::endl;
    }
};

class OuterClass {
public:
    class InnerClass : public BaseClass {
    public:
        void print() override {
            std::cout << "InnerClass object." << std::endl;
        }
    };
};

int main() {
    OuterClass::InnerClass ic;
    ic.print(); // Call the print method of the member class

    return 0;
}
Share your love