Unit 6 - Notes

CSE101 3 min read

Unit 6: Derived types including structures and unions

1. Structures in C

A Structure is a user-defined data type in C/C++ that allows you to combine data items of different kinds. While arrays hold multiple elements of the same type, structures hold elements of different types.

Declaration of a Structure

The struct keyword is used to declare a structure. The variables declared inside the structure are called members or fields.

C
struct Student {
    int roll_no;       // 4 bytes
    char name[20];     // 20 bytes
    float marks;       // 4 bytes
};

Definition and Initialization

Declaring the structure blueprint does not allocate memory. Memory is allocated when a structure variable (object) is defined.

Definition:

C
struct Student s1, s2; // Allocates memory for s1 and s2

Initialization:
You can initialize a structure at the time of declaration or later.

C
// Method 1: Compile-time initialization
struct Student s1 = {101, "Alice", 92.5};

// Method 2: Designated initializers (C99 standard)
struct Student s2 = {.marks = 88.0, .roll_no = 102, .name = "Bob"};

A detailed memory layout diagram illustrating a C Structure named 'Student'. The diagram should show...
AI-generated image — may contain inaccuracies
, 20 bytes)" colored in light green. The third section is "marks (float, 4 bytes)" colored in light orange. Above the block, label it "struct Student s1". Below the block, show the total size calculation: "Total Memory = 4 + 20 + 4 = 28 bytes". Use clear, professional fonts and straight lines.]

Accessing Structure Members

The Member Access Operator (dot operator .) is used to access individual members of a structure.

C
s1.roll_no = 105;
printf("Name: %s", s1.name);


2. Structures and Pointers

We can create a pointer that points to a structure variable. This is useful for dynamic memory allocation and passing structures to functions efficiently.

Declaration and Access

When accessing a member through a pointer, we cannot use the dot operator directly because of operator precedence. We use the Arrow Operator (->).

C
struct Student s1 = {101, "Alice", 90.5};
struct Student *ptr = &s1;

// Accessing members
printf("%d", (*ptr).roll_no); // Method 1: Dereference then dot (cumbersome)
printf("%d", ptr->roll_no);   // Method 2: Arrow operator (preferred)


3. Nested Structures

A structure can contain another structure as one of its members. This is called nesting.

C
struct Date {
    int day;
    int month;
    int year;
};

struct Employee {
    int id;
    char name[20];
    struct Date dob; // Nested Structure
};

int main() {
    struct Employee e1;
    e1.id = 1001;
    e1.dob.day = 15; // Accessing nested member
    e1.dob.month = 8;
    e1.dob.year = 1995;
}


4. Unions

A Union is similar to a structure, but with a critical difference in memory allocation. In a structure, each member has its own storage location. In a union, all members share the same memory location.

Declaration of a Union

C
union Data {
    int i;
    float f;
    char str[20];
};

Memory Allocation Difference

  • Size of Union: Equal to the size of its largest member. In the example above, str[20] is the largest, so the union size is 20 bytes.
  • Behavior: You can only use one member at a time. Assigning a value to one member overwrites the values of others.

A comparison diagram titled "Structure vs. Union Memory Allocation". The left side shows "Structure"...
AI-generated image — may contain inaccuracies


5. Concepts and Basics of C++ Programming

C++ extends C by adding Object-Oriented Programming (OOP) features.

Key Concepts

  1. Classes & Objects: The building blocks of OOP.
  2. Encapsulation: Wrapping data and functions into a single unit (Class).
  3. Abstraction: Hiding internal details and showing only functionality.
  4. Inheritance: Creating new classes from existing ones.
  5. Polymorphism: Ability to take multiple forms (e.g., function overloading).

Reading and Writing Data (cin and cout)

C++ uses the iostream library.

  • cout (Character OUTput): Used with the insertion operator << to print to the console.
  • cin (Character INput): Used with the extraction operator >> to take input.

CPP
#include <iostream>
using namespace std;

int main() {
    int age;
    cout << "Enter your age: "; // Writing to console
    cin >> age;                 // Reading from keyboard
    cout << "You are " << age << " years old." << endl;
    return 0;
}


6. Classes and Objects in C++

Creating Classes

A class is a blueprint for objects. It allows data hiding via access specifiers (public, private, protected). By default, members are private.

CPP
class Rectangle {
    private:
        int length;
        int width;
    
    public:
        // Member function to set data
        void setDimensions(int l, int w) {
            length = l;
            width = w;
        }
        
        // Member function to calculate area
        int area() {
            return length * width;
        }
};

Class Objects and Accessing Members

CPP
int main() {
    Rectangle rect1; // Creating an object
    
    // rect1.length = 10; // ERROR: length is private
    
    rect1.setDimensions(5, 10); // Accessing public member function
    cout << "Area: " << rect1.area(); 
    return 0;
}


7. Inline and Non-inline Member Functions

Inline Functions

A function defined inside the class definition is implicitly inline. Alternatively, the inline keyword can be used. The compiler replaces the function call with the actual code to save function calling overhead (context switching).

CPP
class Demo {
public:
    void display() { // Implicitly Inline
        cout << "Hello";
    }
};

Non-inline Functions

Functions defined outside the class using the Scope Resolution Operator (::). These are treated as normal functions.

CPP
class Demo {
public:
    void display(); // Declaration inside
};

// Definition outside
void Demo::display() {
    cout << "Hello";
}


8. Static Data Members and Member Functions

Static Data Members

A variable declared as static inside a class is a Class Variable.

  • Only one copy exists for the entire class, shared by all objects.
  • It must be defined outside the class.

Static Member Functions

  • Can only access static data members and other static member functions.
  • Called using the class name, not an object.

CPP
class Counter {
    static int count; // Static declaration
public:
    static void showCount() { // Static function
        cout << "Count: " << count << endl;
    }
};

int Counter::count = 0; // Definition outside class

int main() {
    Counter::showCount(); // Calling without object
}


9. Differences: Structures, Unions, Enumerations, Classes

Feature Structure (struct) Union (union) Enumeration (enum) Class (class)
Concept Group of diff. data types. Group sharing memory. List of named integer constants. Blueprint for objects (Data + Methods).
Memory Sum of all members. Size of largest member. Size of an integer. Depends on data members.
Access All members active simultaneously. Only one member active at a time. Holds one constant value at a time. Encapsulates data & methods.
Visibility Default is public. Default is public. Public (Global/Scope based). Default is private.
Use Case Records (e.g., Student info). Memory constrained systems. State machines, flags. Object Oriented Programming.

10. Procedural vs. Object-Oriented Programming

Procedural Programming (POP)

  • Focus: On functions and logical steps (algorithms).
  • Structure: Large programs are divided into functions.
  • Data Access: Global data is often moved freely from function to function (less secure).
  • Approach: Top-Down approach.
  • Example: C, Pascal.

Object-Oriented Programming (OOP)

  • Focus: On objects and data.
  • Structure: Programs are divided into objects.
  • Data Access: Data is hidden (encapsulated) and cannot be accessed by external functions easily.
  • Approach: Bottom-Up approach.
  • Example: C++, Java, Python.

A conceptual diagram contrasting Procedural Oriented Programming (POP) and Object Oriented Programmi...
AI-generated image — may contain inaccuracies