Lesson 09-C++ Classes

Class Definition

In C++, a class is a user-defined data type that allows you to encapsulate data (member variables) and functions (member functions) together. A class definition typically includes the following parts:

  • Class Name: Identifies the name of the class.
  • Member Variables: The data members of the class, used to store the state of the class.
  • Member Functions: The methods of the class, used to define the behavior of the class.
  • Access Specifiers: public, private, protected, used to control the access permissions of members.
class Rectangle {
public:
    // Constructor
    Rectangle(int width, int height) : w(width), h(height) {}

    // Member functions
    int Area() const {
        return w * h;
    }

    int Perimeter() const {
        return 2 * (w + h);
    }

    // Member variables
private:
    int w; // Width
    int h; // Height
};

Class Objects

A class object is an instance of a class. When you create an object of a class, memory is allocated for that class, and you can use the object to access the class’s member variables and member functions.

int main() {
    // Create an object of the Rectangle class
    Rectangle r1(5, 10);

    // Access member functions
    std::cout << "Area: " << r1.Area() << std::endl;
    std::cout << "Perimeter: " << r1.Perimeter() << std::endl;

    return 0;
}

Class Member Functions and Member Variables

Member Functions

Member functions are part of the class, used to define the behavior of the class. Member functions can be defined inside the class body or outside the class body.

// Member functions defined outside the class body
class Rectangle {
public:
    Rectangle(int width, int height) : w(width), h(height) {}

    int Area() const; // Declaration
    int Perimeter() const; // Declaration

private:
    int w;
    int h;
};

// Member functions defined outside the class body
int Rectangle::Area() const {
    return w * h;
}

int Rectangle::Perimeter() const {
    return 2 * (w + h);
}

Member Variables

Member variables are the data members of the class, used to store the state of the class. Member variables can be of any data type and can be declared as public, private, or protected.

class Rectangle {
public:
    Rectangle(int width, int height) : w(width), h(height) {}

    int Area() const {
        return w * h;
    }

    int Perimeter() const {
        return 2 * (w + h);
    }

private:
    int w; // Width
    int h; // Height
};

Access Control

  • public: Public members can be accessed from anywhere.
  • private: Private members can only be accessed within the member functions of the class.
  • protected: Protected members can be accessed within the member functions of the class and also in derived classes.
class Rectangle {
public:
    Rectangle(int width, int height) : w(width), h(height) {}

    int Area() const {
        return w * h;
    }

    // Public member variables
    int w; // Width
    int h; // Height
};

// Using public member variables
int main() {
    Rectangle r1(5, 10);
    std::cout << "Width: " << r1.w << std::endl;
    std::cout << "Height: " << r1.h << std::endl;

    return 0;
}

this Pointer

Definition of this Pointer

In C++, the this pointer is a special pointer that points to the object calling the member function. The this pointer exists only in non-static member functions and is an implicit first parameter. This means that when you access member variables in a member function, you are actually accessing them indirectly through the this pointer.

Characteristics of this Pointer

  • Type: The type of the this pointer is usually a const or non-const pointer type, depending on the definition of the member function.
    • If the member function is non-const, the type of the this pointer is ClassName*.
    • If the member function is const, the type of the this pointer is const ClassName*.
    • Implicit Passing: The this pointer is automatically passed to the member function without needing to be explicitly passed in the function call.
  • Uniqueness: The this pointer of each object points to the address of that object, so the this pointers of different objects point to different addresses.
  • Unavailability: The this pointer cannot be used in static member functions because static member functions do not belong to a specific object.

Uses of this Pointer

  • Referencing Member Variables: The this pointer can be used to access the member variables of the current object.
  • Passing the Current Object: The this pointer can be passed as a parameter to other functions or member functions.
  • Avoiding Naming Conflicts: When a local variable in a member function has the same name as a member variable, you can use this->member to explicitly access the member variable.

Code Example

Let’s demonstrate the use of the this pointer with a specific example.

#include <iostream>

class Rectangle {
public:
    Rectangle(int width, int height) : w(width), h(height) {}

    void SetWidth(int width) {
        w = width;
    }

    int GetWidth() const {
        return w;
    }

    void PrintInfo() const {
        std::cout << "Width: " << this->w << ", Height: " << this->h << std::endl;
    }

private:
    int w;
    int h;
};

int main() {
    Rectangle r1(5, 10);

    r1.PrintInfo(); // Output: Width: 5, Height: 10

    r1.SetWidth(7); // Modify width
    r1.PrintInfo(); // Output: Width: 7, Height: 10

    return 0;
}

Notes on this Pointer

  • Avoid Modifying this Pointer: Do not attempt to modify the value of the this pointer inside a member function, as this may lead to undefined behavior.
  • Check Validity of this Pointer: Before using the this pointer inside a member function, it is best to check if it is nullptr to avoid accessing invalid memory.

this Pointer and const Member Functions

  • When a member function is declared as const, the type of the this pointer becomes const ClassName*, which means the member function cannot modify member variables.
  • You can temporarily remove the const restriction using const_cast inside the member function, but this is generally not recommended as it may violate the semantics of const.
class MyClass {
public:
    void SetData(int data) {
        data_ = data;
    }

    void GetData() const {
        std::cout << "Data: " << data_ << std::endl;
    }

    void ModifyData() const {
        // Error: Attempt to modify member variable in const member function
        // data_ = 5; // Compilation error

        // Temporarily remove const restriction (not recommended)
        const_cast<MyClass*>(this)->data_ = 5;
    }

private:
    int data_;
};

Static Class Members

Static Member Variables

Static member variables are a single copy shared among all objects of the class. This means that no matter how many objects of the class are created, there is only one instance of the static member variable.

Characteristics

  • Definition and Initialization: Static member variables need to be declared inside the class and initialized outside the class.
  • Storage Location: Static member variables are stored in the global data area, not on the stack or heap.
  • Access: Static member variables can be accessed through the class name or object name.
  • Lifetime: Static member variables exist throughout the lifetime of the program.
#include <iostream>

class MyClass {
public:
    static int count; // Static member variable declaration

    MyClass() {
        ++count; // Increment the counter for each object created
    }
};

// Initialization of static member variable
int MyClass::count = 0;

int main() {
    MyClass obj1, obj2, obj3;

    std::cout << "Count: " << MyClass::count << std::endl; // Output: Count: 3

    return 0;
}

Static Member Functions

Static member functions are part of the class but do not depend on any specific object instance. Static member functions can access the class’s static member variables but cannot access non-static member variables.

Characteristics

  • Declaration and Definition: Static member functions can be declared inside the class and defined inside or outside the class.
  • Access: Static member functions can be accessed through the class name or object name.
  • Role: Static member functions are typically used to implement operations related to the class but not requiring specific object state.
#include <iostream>

class MyClass {
public:
    static int count; // Static member variable declaration
    static void incrementCount(); // Static member function declaration

    MyClass() {
        ++count; // Increment the counter for each object created
    }
};

// Initialization of static member variable
int MyClass::count = 0;

// Definition of static member function
void MyClass::incrementCount() {
    ++count;
}

int main() {
    MyClass::incrementCount(); // Call static member function directly through class name

    MyClass obj1, obj2, obj3;

    std::cout << "Count: " << MyClass::count << std::endl; // Output: Count: 4

    return 0;
}

Difference Between Static Member Variables and Non-Static Member Variables

  • Storage Location: Static member variables are stored in the global data area, while non-static member variables are stored in each object instance.
  • Access Method: Static member variables can be accessed through the class name or object name, while non-static member variables can only be accessed through the object name.
  • Lifetime: Static member variables exist throughout the program’s lifetime, while the lifetime of non-static member variables is the same as the object’s.

Difference Between Static Member Functions and Non-Static Member Functions

  • Access Permissions: Static member functions can only access static member variables and other static member functions, while non-static member functions can access all members of the class.
  • this Pointer: Static member functions do not have a this pointer, while non-static member functions have a this pointer pointing to the current object.
  • Call Method: Static member functions can be called through the class name or object name, while non-static member functions can only be called through the object name.

Example Code

Here is an example code demonstrating the use of static member variables and static member functions:

#include <iostream>

class Counter {
public:
    static int count; // Static member variable declaration

    Counter() {
        ++count; // Increment the counter for each object created
    }

    static void showCount() { // Static member function
        std::cout << "Count: " << count << std::endl;
    }
};

// Initialization of static member variable
int Counter::count = 0;

int main() {
    Counter c1, c2, c3;

    Counter::showCount(); // Output: Count: 3

    return 0;
}

Const Class Members

Const Member Variables

Const member variables are member variables declared with the const keyword. Once initialized, their values cannot be modified. Const member variables must be initialized in the constructor’s initialization list.

#include <iostream>

class MyClass {
public:
    MyClass(int value) : constVar(value) {} // Initialize const member variable

    void print() const {
        std::cout << "Const var: " << constVar << std::endl;
    }

private:
    const int constVar; // Const member variable
};

int main() {
    MyClass obj(42);
    obj.print(); // Output: Const var: 42

    return 0;
}

Const Member Functions

Const member functions are member functions declared with the const keyword. They cannot modify any non-static member variables of the class and cannot call non-const member functions.

#include <iostream>

class MyClass {
public:
    MyClass(int value) : var(value) {}

    void print() const { // Const member function
        std::cout << "Var: " << var << std::endl;
    }

private:
    int var;
};

int main() {
    const MyClass obj(42);
    obj.print(); // Can call const member function on const object

    return 0;
}

Mutable Member Variables

Mutable member variables are member variables declared with the mutable keyword. They can be modified even in const member functions.

#include <iostream>

class MyClass {
public:
    MyClass(int value) : var(value) {}

    void modifyMutable() const {
        mutableVar = 100; // Can modify mutable member in const function
    }

    void print() const {
        std::cout << "Mutable var: " << mutableVar << std::endl;
    }

private:
    mutable int mutableVar = 0;
};

int main() {
    const MyClass obj(42);
    obj.modifyMutable();
    obj.print(); // Output: Mutable var: 100

    return 0;
}

Example Code

Here is an example code demonstrating const member variables, const member functions, and mutable member variables:

#include <iostream>

class ConstExample {
public:
    ConstExample(int val) : constVar(val) {}

    void modifyMutable() const {
        mutableVar = 100;
    }

    void print() const {
        std::cout << "Const var: " << constVar << ", Mutable var: " << mutableVar << std::endl;
    }

private:
    const int constVar;
    mutable int mutableVar = 0;
};

int main() {
    const ConstExample obj(42);
    obj.modifyMutable();
    obj.print(); // Output: Const var: 42, Mutable var: 100

    return 0;
}

Friend Functions and Friend Classes

Friend Functions

A friend function is a non-member function that can access the private and protected members of a class. To declare a friend function, use the friend keyword inside the class definition.

#include <iostream>

class MyClass {
private:
    int privateVar = 42;

    // Friend function declaration
    friend void friendFunction(const MyClass& obj);
};

void friendFunction(const MyClass& obj) {
    std::cout << "Private var: " << obj.privateVar << std::endl;
}

int main() {
    MyClass obj;
    friendFunction(obj); // Output: Private var: 42

    return 0;
}

Friend Classes

A friend class is a class that can access the private and protected members of another class. To declare a friend class, use the friend keyword followed by the class name inside the class definition.

#include <iostream>

class FriendClass {
public:
    void accessPrivate(const MyClass& obj);
};

class MyClass {
private:
    int privateVar = 42;

    // Friend class declaration
    friend class FriendClass;
};

void FriendClass::accessPrivate(const MyClass& obj) {
    std::cout << "Private var: " << obj.privateVar << std::endl;
}

int main() {
    MyClass obj;
    FriendClass friendObj;
    friendObj.accessPrivate(obj); // Output: Private var: 42

    return 0;
}

Friend Member Functions

A friend member function is a member function of one class that can access the private and protected members of another class. To declare a friend member function, use the friend keyword followed by the fully qualified member function name inside the class definition.

#include <iostream>

class FriendClass {
public:
    void accessPrivate(const MyClass& obj);
};

class MyClass {
private:
    int privateVar = 42;

    // Friend member function declaration
    friend void FriendClass::accessPrivate(const MyClass& obj);
};

void FriendClass::accessPrivate(const MyClass& obj) {
    std::cout << "Private var: " << obj.privateVar << std::endl;
}

int main() {
    MyClass obj;
    FriendClass friendObj;
    friendObj.accessPrivate(obj); // Output: Private var: 42

    return 0;
}

Example Code

Here is an example code demonstrating friend functions, friend classes, and friend member functions:

#include <iostream>

class FriendClass {
public:
    void accessPrivate(const MyClass& obj);
};

class MyClass {
private:
    int privateVar = 42;

    friend void friendFunction(const MyClass& obj);
    friend class FriendClass;
    friend void FriendClass::accessPrivate(const MyClass& obj);
};

void friendFunction(const MyClass& obj) {
    std::cout << "Friend function: " << obj.privateVar << std::endl;
}

void FriendClass::accessPrivate(const MyClass& obj) {
    std::cout << "Friend member function: " << obj.privateVar << std::endl;
}

int main() {
    MyClass obj;
    friendFunction(obj); // Output: Friend function: 42

    FriendClass friendObj;
    friendObj.accessPrivate(obj); // Output: Friend member function: 42

    return 0;
}

Constructors

Default Constructor

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

class MyClass {
public:
    MyClass() { // Default constructor
        std::cout << "Default constructor called." << std::endl;
    }
};

int main() {
    MyClass obj; // Calls the default constructor
    return 0;
}

Parameterized Constructor

A parameterized constructor is a constructor that accepts parameters and is used to initialize member variables.

class MyClass {
public:
    MyClass(int value) : val(value) { // Parameterized constructor
        std::cout << "Parameterized constructor called with value: " << val << std::endl;
    }

private:
    int val;
};

int main() {
    MyClass obj(42); // Calls the parameterized constructor
    return 0;
}

Copy Constructor

The copy constructor is a constructor that accepts a reference to an object of the same class and is used to copy the state of the object.

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

    MyClass(const MyClass& other) : val(other.val) { // Copy constructor
        std::cout << "Copy constructor called." << std::endl;
    }

private:
    int val;
};

int main() {
    MyClass obj1(42);
    MyClass obj2 = obj1; // Calls the copy constructor
    return 0;
}

Move Constructor

The move constructor is a constructor that accepts an rvalue reference to an object of the same class and is used to transfer resources from a temporary object.

#include <utility>

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

    MyClass(MyClass&& other) noexcept : val(std::move(other.val)) { // Move constructor
        std::cout << "Move constructor called." << std::endl;
    }

private:
    int val;
};

int main() {
    MyClass obj1(42);
    MyClass obj2 = std::move(obj1); // Calls the move constructor
    return 0;
}

Delegating Constructor

A delegating constructor is a constructor that delegates the initialization work to another constructor of the same class.

class MyClass {
public:
    MyClass() : MyClass(0) { // Delegating constructor
        std::cout << "Delegating constructor called." << std::endl;
    }

    MyClass(int value) : val(value) {
        std::cout << "Parameterized constructor called with value: " << val << std::endl;
    }

private:
    int val;
};

int main() {
    MyClass obj; // Calls the delegating constructor
    return 0;
}

Explicit Constructor

An explicit constructor is a constructor declared with the explicit keyword and cannot be used for implicit type conversions.

class MyClass {
public:
    explicit MyClass(int value) : val(value) { // Explicit constructor
        std::cout << "Explicit constructor called." << std::endl;
    }

private:
    int val;
};

int main() {
    // MyClass obj = 42; // Compilation error: implicit conversion not allowed
    MyClass obj(42); // Explicit call
    return 0;
}

Example Code

Here is an example code demonstrating different types of constructors:

#include <iostream>
#include <utility>

class ConstructorExample {
public:
    ConstructorExample() : val(0) {
        std::cout << "Default constructor." << std::endl;
    }

    ConstructorExample(int value) : val(value) {
        std::cout << "Parameterized constructor." << std::endl;
    }

    ConstructorExample(const ConstructorExample& other) : val(other.val) {
        std::cout << "Copy constructor." << std::endl;
    }

    ConstructorExample(ConstructorExample&& other) noexcept : val(std::move(other.val)) {
        std::cout << "Move constructor." << std::endl;
    }

private:
    int val;
};

int main() {
    ConstructorExample defaultObj; // Default constructor
    ConstructorExample paramObj(42); // Parameterized constructor
    ConstructorExample copyObj = paramObj; // Copy constructor
    ConstructorExample moveObj = std::move(paramObj); // Move constructor

    return 0;
}

Destructor

Destructor Definition

A destructor is a special member function that is automatically called when an object is destroyed. The destructor is used to release resources occupied by the object, such as dynamically allocated memory, file handles, etc.

Destructor Syntax

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

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

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
}

Operator Overloading

Operator Overloading Definition

Operator overloading allows you to redefine the behavior of operators for user-defined types. This makes the code more intuitive and readable.

Operator Overloading Syntax

Operators can be overloaded as member functions or non-member functions. For member functions, the left operand is implicitly the this pointer.

class Complex {
public:
    Complex(double r = 0, double i = 0) : real(r), imag(i) {}

    // Overload + operator as member function
    Complex operator+(const Complex& other) const {
        return Complex(real + other.real, imag + other.imag);
    }

private:
    double real;
    double imag;
};

Overloadable Operators

Most operators in C++ can be overloaded, including arithmetic operators, comparison operators, assignment operators, etc. However, some operators cannot be overloaded, such as ::, .*, ., ?:.

Overloading Rules

  • Unary Operators: Can be overloaded as member functions with no parameters or non-member functions with one parameter.
  • Binary Operators: Can be overloaded as member functions with one parameter or non-member functions with two parameters.
  • Assignment Operator: Must be overloaded as a member function.
  • Subscript Operator: Must be overloaded as a member function.
  • Function Call Operator: Must be overloaded as a member function.

Friend Functions and Operator Overloading

Friend functions can be used to overload operators that require access to private members.

class Complex {
public:
    Complex(double r = 0, double i = 0) : real(r), imag(i) {}

    friend Complex operator+(const Complex& a, const Complex& b);

private:
    double real;
    double imag;
};

Complex operator+(const Complex& a, const Complex& b) {
    return Complex(a.real + b.real, a.imag + b.imag);
}

Example Code

Here is an example code demonstrating operator overloading:

#include <iostream>

class Vector {
public:
    Vector(int x = 0, int y = 0) : x_(x), y_(y) {}

    Vector operator+(const Vector& other) const {
        return Vector(x_ + other.x_, y_ + other.y_);
    }

    void print() const {
        std::cout << "(" << x_ << ", " << y_ << ")" << std::endl;
    }

private:
    int x_;
    int y_;
};

int main() {
    Vector v1(1, 2);
    Vector v2(3, 4);
    Vector v3 = v1 + v2;
    v3.print(); // Output: (4, 6)
    return 0;
}

Type Conversion

Implicit Type Conversion

Implicit type conversion is automatically performed by the compiler when needed, such as converting int to double.

int main() {
    int i = 42;
    double d = i; // Implicit conversion from int to double
    return 0;
}

Explicit Type Conversion

Explicit type conversion is performed using cast operators, such as static_cast, dynamic_cast, const_cast, reinterpret_cast.

int main() {
    double d = 3.14;
    int i = static_cast<int>(d); // Explicit conversion from double to int
    return 0;
}

User-Defined Type Conversion

User-defined type conversion allows defining how a user-defined type is converted to another type using conversion operators.

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

    operator int() const { // Conversion operator
        return val;
    }

private:
    int val;
};

int main() {
    MyInt mi(42);
    int i = mi; // User-defined conversion
    return 0;
}

Example Code

Here is an example code demonstrating type conversion:

#include <iostream>

class Distance {
public:
    Distance(double meters) : m(meters) {}

    operator double() const { // Conversion to double
        return m;
    }

private:
    double m;
};

int main() {
    Distance dist(100.0);
    double d = dist; // User-defined conversion
    std::cout << "Distance in meters: " << d << std::endl;
    return 0;
}

Pointers to Members

Pointers to Member Variables

Pointers to member variables are pointers that point to non-static member variables of a class. They need to be bound to a specific object to access the member variable.

#include <iostream>

class MyClass {
public:
    int x;
};

int main() {
    MyClass obj;
    int MyClass::*px = &MyClass::x; // Pointer to member variable

    obj.*px = 10; // Access member variable through pointer

    std::cout << "Value of x: " << obj.x << std::endl; // Output: Value of x: 10

    return 0;
}

Pointers to Member Functions

Pointers to member functions are pointers that point to non-static member functions of a class. They need to be bound to a specific object to call the member function.

#include <iostream>

class MyClass {
public:
    int get_x() const { return x; }
    void set_x(int value) { x = value; }

private:
    int x;
};

int main() {
    MyClass obj;

    int (MyClass::*getter)() const = &MyClass::get_x; // Pointer to member function
    void (MyClass::*setter)(int) = &MyClass::set_x;

    obj.set_x(10);

    std::cout << "Value of x: " << (obj.*getter)() << std::endl; // Output: Value of x: 10

    return 0;
}

Special Features of Pointers to Member Functions

Pointers to member functions are more complex than ordinary function pointers because they require additional information to determine the this pointer. Pointers to member functions actually contain two parts:

  • ptr: A pointer to a global function that accepts a this pointer as a parameter and calls the actual member function.
  • adj: An offset to adjust the this pointer so that the this pointer can correctly point to the calling object.

Example Code

#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

    return 0;
}

Pointers to Virtual Member Functions

Pointers to virtual member functions require extra space to store the offset address in the virtual function table and other information.

Example Code

#include <iostream>

class Base {
public:
    virtual void print() const { std::cout << "Base class" << std::endl; }
};

class Derived : public Base {
public:
    void print() const override { std::cout << "Derived class" << std::endl; }
};

int main() {
    Derived d;

    void (Base::*ptr)() const = &Derived::print; // Pointer to virtual member function

    (d.*ptr)(); // Call member function

    return 0;
}

Unions

Basic Concept of Unions

A union is a data type similar to a struct, but it has the following characteristics:

  • All members share the same memory segment.
  • At any moment, only one member’s value is valid.
  • The size of the union is equal to the size of its largest member.

Definition of Unions

The definition syntax of a union is similar to that of a struct, but uses the keyword union.

union MyUnion {
    int i;
    float f;
    char c;
};

In this example, the size of MyUnion will be at least equal to the size of float, because float is the largest type among the three members.

Use of Unions

Unions can be used to save memory space, which is particularly useful in embedded system development. However, note that since multiple members share the same memory, special care must be taken when using unions to ensure no data races occur.

#include <iostream>

union MyUnion {
    int i;
    float f;
    char c;
};

int main() {
    MyUnion u;

    u.i = 10;
    std::cout << "Integer value: " << u.i << std::endl; // Output: Integer value: 10

    u.f = 3.14f;
    std::cout << "Float value: " << u.f << std::endl; // Output: Float value: 3.14

    u.c = 'A';
    std::cout << "Char value: " << u.c << std::endl; // Output: Char value: A

    return 0;
}

Unions and Type Safety

In C++11 and later versions, std::variant can be used instead of traditional unions to achieve better type safety and compile-time checking.

#include <iostream>
#include <variant>

int main() {
    std::variant<int, float, char> v;

    v = 10;
    std::cout << "Integer value: " << std::get<int>(v) << std::endl; // Output: Integer value: 10

    v = 3.14f;
    std::cout << "Float value: " << std::get<float>(v) << std::endl; // Output: Float value: 3.14

    v = 'A';
    std::cout << "Char value: " << std::get<char>(v) << std::endl; // Output: Char value: A

    return 0;
}

Bit Fields

Bit fields allow you to define multiple fields within an integer type, with each field occupying a specified number of bits. Bit fields are mainly used to save memory or directly manipulate hardware.

Syntax

struct BitFieldStruct {
    unsigned int field1 : 3; // 3 bits
    unsigned int field2 : 5; // 5 bits
    unsigned int field3 : 1; // 1 bit
};

Characteristics

  • Memory Allocation: The total size of the bit field is based on multiples of the integer size of the largest field. For example, if the largest field is 8 bits, the size of the entire bit field struct will be 8 bits or a larger multiple.
  • Bit Field Order: Bit fields are placed from left to right in the order of declaration, with high bits first and low bits last.
  • Adjacent Bit Field Fields: If adjacent bit field fields have different types, the specific implementation may vary across compilers. For example, VC6 does not compress bit fields of different types, while DevC++ does.
  • Non-Bit Field Fields: If non-bit field fields are inserted between bit field fields, compression is usually not performed.

Example Code

#include <iostream>

struct BitFieldStruct {
    unsigned int field1 : 3; // 3 bits
    unsigned int field2 : 5; // 5 bits
    unsigned int field3 : 1; // 1 bit
};

int main() {
    BitFieldStruct bf;
    bf.field1 = 5; // Binary: 101
    bf.field2 = 20; // Binary: 10100
    bf.field3 = 1; // Binary: 1

    std::cout << "Field1: " << bf.field1 << std::endl;
    std::cout << "Field2: " << bf.field2 << std::endl;
    std::cout << "Field3: " << bf.field3 << std::endl;

    return 0;
}

Nested Classes

A nested class is a class defined within the definition of another class. A nested class can access all members of the enclosing class, including private members. However, the enclosing class cannot directly access the private members of the nested class.

Syntax

class OuterClass {
public:
    class NestedClass {
    public:
        void useOuterMember() {
            // Can access members of OuterClass
            outerMember = 10;
        }
    };

private:
    int outerMember;
};

Example Code

#include <iostream>

class OuterClass {
public:
    class NestedClass {
    public:
        void useOuterMember(OuterClass& outer) {
            outer.outerMember = 10;
        }
    };

private:
    int outerMember;
};

int main() {
    OuterClass outer;
    OuterClass::NestedClass nested;

    nested.useOuterMember(outer);

    std::cout << "Outer member: " << outer.outerMember << std::endl; // Output: Outer member: 10

    return 0;
}

Namespace Member Classes

Namespace member classes are classes defined within a namespace. Namespaces are used to organize related classes and other types.

Syntax

namespace MyNamespace {
    class MyClass {
    public:
        void doSomething() {
            std::cout << "Doing something in MyNamespace." << std::endl;
        }
    };
}

Example Code

#include <iostream>

namespace MyNamespace {
    class MyClass {
    public:
        void doSomething() {
            std::cout << "Doing something in MyNamespace." << std::endl;
        }
    };
}

int main() {
    MyNamespace::MyClass myObj;
    myObj.doSomething();

    return 0;
}

Local Classes

Syntax

void someFunction() {
    class LocalClass {
    public:
        void doSomething() {
            std::cout << "Doing something in LocalClass." << std::endl;
        }
    };
}

Example Code

#include <iostream>

void someFunction() {
    class LocalClass {
    public:
        void doSomething() {
            std::cout << "Doing something in LocalClass." << std::endl;
        }
    };

    LocalClass localObj;
    localObj.doSomething();
}

int main() {
    someFunction();

    return 0;
}
Share your love