Unit 6 - Notes
CSE101
Unit 6: Derived types including structures and unions / Concepts and Basics of C++ Programming
1. Structures
Declaration of a Structure
A structure is a user-defined data type in C/C++ that allows you to combine data items of different kinds (e.g., integers, floats, chars) into a single logical unit.
Syntax:
struct StructureName {
dataType member1;
dataType member2;
// ...
};
- The keyword
structstarts the declaration. StructureName(or tag) is the name of the new type.- The definition must end with a semicolon
;.
Definition and Initialization of Structures
Defining a structure variable allocates memory. Initialization assigns values to members at the time of definition.
Example:
struct Student {
int rollNo;
char name[50];
float marks;
};
int main() {
// Definition
struct Student s1;
// Definition with Initialization
struct Student s2 = {101, "Alice", 92.5};
// C++ allow omitting the 'struct' keyword during instantiation
Student s3 = {102, "Bob", 88.0};
return 0;
}
Accessing Structure Members
Structure members are accessed using the Member Access Operator (also known as the Dot Operator .).
Syntax: structureVariable.memberName
s1.rollNo = 105; // Assigning value
cout << s2.marks; // Reading value
Structures and Pointers
You can create a pointer that points to a structure. To access members via a pointer, you use the Arrow Operator (->).
Syntax: pointerName->memberName
Example:
struct Point {
int x;
int y;
};
int main() {
Point p1 = {10, 20};
Point *ptr = &p1; // ptr holds the address of p1
// Accessing using pointer
ptr->x = 30; // Equivalent to (*ptr).x = 30;
// Accessing using dot operator on the object
// p1.x is now 30
}
Nested Structures
A structure can be a member of another structure. This is called nesting.
Example:
struct Date {
int day;
int month;
int year;
};
struct Employee {
int id;
char name[20];
struct Date joiningDate; // Nested structure
};
int main() {
Employee e1;
e1.id = 1;
// Accessing nested members
e1.joiningDate.day = 15;
e1.joiningDate.year = 2023;
}
2. Unions
Declaration of a Union
A Union is similar to a structure, but all members share the same memory location. The size of the union is equal to the size of its largest member. Only one member can contain a valid value at any given time.
Syntax:
union Data {
int i;
float f;
char str[20];
};
Memory Usage Example:
- In the example above,
intis 4 bytes,floatis 4 bytes,stris 20 bytes. - The size of
union Datais 20 bytes. - If it were a
struct, the size would be roughly 28 bytes (depending on padding).
Accessing Union Members:
Same as structures, using the dot operator (.) or arrow operator (->) for pointers. Note that writing to one member overwrites the others.
3. Basics of C++ Programming
Reading and Writing Data (cin and cout)
C++ uses the iostream library for Input/Output.
-
Standard Output (
cout):- Stands for "Character Output".
- Used with the Insertion Operator (
<<). - Sends data to the standard output stream (screen).
- Example:
std::cout << "Hello World" << std::endl;
-
Standard Input (
cin):- Stands for "Character Input".
- Used with the Extraction Operator (
>>). - Reads data from the standard input stream (keyboard).
- Example:
std::cin >> variableName;
Example:
#include <iostream>
using namespace std;
int main() {
int age;
cout << "Enter your age: "; // Output
cin >> age; // Input
cout << "You are " << age << " years old.";
return 0;
}
4. Object-Oriented Programming (OOP) in C++
Differences between Procedural and OOP Paradigms
| Feature | Procedural Programming (POP) | Object-Oriented Programming (OOP) |
|---|---|---|
| Focus | Focuses on functions and steps (algorithms). | Focuses on data and objects. |
| Data Security | Less secure; data moves freely (Global data). | More secure; data is hidden (Encapsulation). |
| Approach | Top-Down approach. | Bottom-Up approach. |
| Reusability | Limited reusability. | High reusability via Inheritance and Polymorphism. |
| Examples | C, Pascal. | C++, Java, Python. |
Creating Classes
A Class is a blueprint for creating objects. It encapsulates data (attributes) and functions (methods) into a single unit. By default, members of a class are private.
Syntax:
class ClassName {
private:
// Data members (variables)
// Member functions meant for internal use
public:
// Data members
// Member functions accessible from outside
};
Class Objects
An Object is an instance of a class. When a class is defined, no memory is allocated. Memory is allocated when an object is instantiated.
Syntax: ClassName objectName;
Accessing Class Members
Public members are accessed using the dot operator (.). Private members cannot be accessed directly from outside the class.
Example:
class Rectangle {
private:
int length; // Private data
int width;
public:
// Public function to set data
void setDimensions(int l, int w) {
length = l;
width = w;
}
// Public function to get area
int getArea() {
return length * width;
}
};
int main() {
Rectangle rect; // Creating Object
rect.setDimensions(5, 4); // Accessing member function
cout << rect.getArea(); // Output: 20
// rect.length = 10; // Error: length is private
}
5. Member Functions
Inline Functions
An inline function is a function where the compiler replaces the function call with the actual code of the function to reduce function call overhead.
- Implicit Inline: Functions defined inside the class definition are automatically inline.
- Explicit Inline: Using the
inlinekeyword.
Example:
class Math {
public:
// Defined inside class (Implicit Inline)
int add(int a, int b) {
return a + b;
}
};
Non-inline Member Functions
These are declared inside the class but defined outside the class using the Scope Resolution Operator (::). This keeps the class definition clean.
Example:
class Math {
public:
int multiply(int a, int b); // Declaration only
};
// Definition outside
int Math::multiply(int a, int b) {
return a * b;
}
6. Static Members
Static Data Members
- Declared using the
statickeyword. - One copy per class, shared by all objects of that class.
- Initialized to 0 by default.
- Must be defined outside the class to allocate memory.
Static Member Functions
- Can only access static data members and other static member functions.
- Called using the class name, not a specific object.
Example:
class Box {
private:
static int objectCount; // Static data declaration
public:
Box() {
objectCount++;
}
// Static function
static int getCount() {
return objectCount;
}
};
// Definition and initialization of static member
int Box::objectCount = 0;
int main() {
Box b1, b2, b3;
// Accessing static function via Class Name
cout << Box::getCount(); // Output: 3
}
7. Comparison of Derived Types
Differences between Structures, Unions, Enumerations, and Classes
| Feature | Structure (struct) |
Union (union) |
Enumeration (enum) |
Class (class) |
|---|---|---|---|---|
| Memory Allocation | Sum of size of all members (plus padding). | Size of the largest member only. | Size of an integer (usually). | Sum of size of all data members (plus padding). |
| Member Access | All members can be accessed simultaneously. | Only one member active at a time. | N/A (Holds integer constants). | All members accessed simultaneously. |
| Visibility (Access) | Members are Public by default. | Members are Public by default. | Global or Local scope. | Members are Private by default. |
| Purpose | Grouping related data. | Saving memory when items are mutually exclusive. | Creating named integer constants for readability. | Encapsulation of Data + Functions (OOP). |
| Functions | In C: No functions allowed inside. In C++: Allowed. | Allowed in C++. | No functions allowed. | Functions allowed (fundamental to OOP). |
Note on Enumeration:
An enum is a user-defined type consisting of a set of named integral constants.
enum Color { RED, GREEN, BLUE }; // RED=0, GREEN=1, BLUE=2
Color c = RED;