Structures In C++

Topic asked in February 2022 (CBCS) and July 2022 (CBCS) question papers.

In C++, a structure is a user-defined data type that allows you to group together different variables under a single name. You can define a structure using the struct keyword, declare structure variables, and access members of the structure. Let's go through each of these steps with examples:

Defining a Structure

To define a structure in C++, you use the struct keyword followed by the name of the structure and a set of curly braces enclosing the member variables.

Example:

#include <iostream>
using namespace std;
 
// Defining a structure named 'Person'
struct Person {
    string name;
    int age;
    char gender;
};

Declaring Structure Variables

After defining a structure, you can declare variables of that structure type. This is similar to declaring variables of any other data type.

Example:

// Declaring structure variables
Person person1;

Accessing Members of Structure

You can access the members (variables) of a structure using the dot (.) operator followed by the member name.

Example:

// Accessing and assigning values to structure members
person1.name = "Eniv";
person1.age = 22;
person1.gender = 'M';
 
// Accessing and printing structure members
cout << "Name: " << person1.name << endl;
cout << "Age: " << person1.age << endl;
cout << "Gender: " << person1.gender << endl;

Putting it all together, here's a complete example demonstrating the definition, declaration, and access of structure members:

#include <iostream>
using namespace std;
 
// Defining a structure named 'Person'
struct Person {
    string name;
    int age;
    char gender;
};
 
int main() {
    // Declaring structure variables
    Person person1;
 
    // Accessing and assigning values to structure members
    person1.name = "Eniv";
    person1.age = 22;
    person1.gender = 'M';
 
    // Accessing and printing structure members
    cout << "Person 1:" << endl;
    cout << "Name: " << person1.name << endl;
    cout << "Age: " << person1.age << endl;
    cout << "Gender: " << person1.gender << endl;
 
    return 0;
}

Output:

Person 1:
Name: Eniv
Age: 22
Gender: M

Class In C++

In C++, a class is a user-defined data type that provides a template for creating objects (instances) which encapsulate data and behavior. A class is a blueprint that defines the structure and behavior of an object. It defines the data members and member functions that objects of that class will have. An object is an instance of a class. It is a concrete entity that has its own set of data members and member functions.

Defining a Class

To define a class in C++, you use the class keyword followed by the name of the class and a set of curly braces enclosing the member variables and member functions.

Example:

#include <iostream>
using namespace std;
 
// Defining a class named 'Person'
class Person {
public: // Access specifier
    string name;
    int age;
    char gender;
};

Declaring Objects of Class

After defining a class, you can declare objects (instances) of that class. This is similar to declaring variables of any other data type.

Example:

// Declaring object of class
Person person1;

Accessing Class Members

You can access the members (variables and functions) of a class using the dot (.) operator followed by the member name.

// Accessing and assigning values to class members
person1.name = "Shubham";
person1.age = 22;
person1.gender = 'M';
 
// Accessing and printing class members
cout << "Name: " << person1.name << endl;
cout << "Age: " << person1.age << endl;
cout << "Gender: " << person1.gender << endl;

Putting it all together, here's a complete example demonstrating the definition of a class, declaration of objects, and access of class members:

#include <iostream>
using namespace std;
 
// Defining a class named 'Person'
class Person {
public: // Access specifier
    string name;
    int age;
    char gender;
};
 
int main() {
    // Declaring object of class
    Person person1;
 
    // Accessing and assigning values to class members
    person1.name = "Shubham";
    person1.age = 22;
    person1.gender = 'M';
 
    // Accessing and printing class members
    cout << "Person 1:" << endl;
    cout << "Name: " << person1.name << endl;
    cout << "Age: " << person1.age << endl;
    cout << "Gender: " << person1.gender << endl;
 
    return 0;
}

Output:

Person 1:
Name: Shubham
Age: 22
Gender: M

Difference Between struct and class in C++

Topic asked in May 2024 (NEP) question paper.

StructClass
The data member of the struct is public by default.The data member of the class is private by default.
The structure is defined by using the struct keyword.The class keyword is used to define the class in C++.
The structure cannot be inherited.The class can be inherited.
The structure does not provide security.The class provides high security.
It is mostly used for a small amount of data.It is used for a large amount of data.

Difference between Array and Structure In C++

Topic asked in July 2022 (CBCS) and December 2022 (CBCS) question paper.

FeatureArrayStructure
Data TypesAll elements of an array have the same data type.Each member of a structure can have a different data type.
Memory AllocationContiguous memory allocation for elements of the same data type.Non-contiguous memory allocation for members of different data types.
SizeFixed size, determined at the time of declaration.Variable size, determined by the sum of sizes of its members.
AccessElements are accessed using an index.Members are accessed using the dot (.) operator.
HomogeneityHomogeneous data type (all elements are of the same type).Heterogeneous data type (members can be of different types).

Declaring an Array of Structures

We can declare an array of structures by combining the concepts of arrays and structures. Here's how we can do it:

#include <iostream>
using namespace std;
 
// Define a structure
struct Student {
    string name;
    int rollNumber;
    float marks;
};
 
int main() {
    int SIZE = 3; // Size of the array
    Student students[SIZE]; // Declaration of an array of structures
 
    // Initializing the array of structures
    students[0] = {"Shubham", 1, 85.5};
    students[1] = {"Eniv", 2, 90.0};
    students[2] = {"Vine", 3, 78.3};
 
    // Accessing and printing elements of the array of structures
    for (int i = 0; i < SIZE; ++i) {
        cout << "Student Name: " << students[i].name << endl;
        cout << "Roll Number: " << students[i].rollNumber << endl;
        cout << "Marks: " << students[i].marks << endl;
        cout << endl;
    }
 
    return 0;
}

Output:

Student Name: Shubham
Roll Number: 1
Marks: 85.5

Student Name: Eniv
Roll Number: 2
Marks: 90

Student Name: Vine
Roll Number: 3
Marks: 78.3

Explanation:

In this example, we define a structure Student with three members: name, rollNumber, and marks. Then, we declare an array students of type Student with a fixed size of 3. We initialize the array elements with the details of different students. Finally, we access and print the details of each student using a loop.

Passing Structure Through A Function

Topic asked in July 2022 (CBCS) question paper.

In C++, structures can be passed to functions in several ways:

  1. Pass by Value: When a structure is passed by value, a copy of the entire structure is made and passed to the function. Any modifications made to the structure inside the function do not affect the original structure outside the function.

    #include <iostream>
    using namespace std;
     
    struct Point {
        int x;
        int y;
    };
     
    void printPoint(Point p) {
        p.x = 10; // Modify the x-coordinate of the passed structure
        cout << "Point inside function: (" << p.x << ", " << p.y << ")" << endl;
    }
     
    int main() {
        Point myPoint = {3, 4};
        printPoint(myPoint);
        cout << "Point outside function: (" << myPoint.x << ", " << myPoint.y << ")" << endl;
        return 0;
    }

    Output:

    Point inside function: (10, 4)
    Point outside function: (3, 4)

    Explanation:

    • Inside the printPoint function, the x coordinate of the passed structure p is modified to 10.
    • After returning from the function, the x coordinate of the original myPoint structure remains unchanged (3), demonstrating that modifications inside the function do not affect the original structure.
  2. Pass by Reference (or Address): When a structure is passed by reference, a reference (or pointer) to the original structure is passed to the function. Any modifications made to the structure inside the function affect the original structure outside the function.

    #include <iostream>
    using namespace std;
     
    struct Point {
        int x;
        int y;
    };
     
    void printPoint(Point& p) {
        p.x = 10; // Modify the x-coordinate of the passed structure
        cout << "Point inside function: (" << p.x << ", " << p.y << ")" << endl;
    }
     
    int main() {
        Point myPoint = {3, 4};
        printPoint(myPoint);
        cout << "Point outside function: (" << myPoint.x << ", " << myPoint.y << ")" << endl;
        return 0;
    }

    Output:

    Point inside function: (10, 4)
    Point outside function: (10, 4)

    Explanation:

    • Inside the printPoint function, the x coordinate of the passed structure p is modified to 10.
    • After returning from the function, the x coordinate of the original myPoint structure is also 10, demonstrating that modifications inside the function affect the original structure since it was passed by reference.

OOP

Topic asked in July 2022 (CBCS) question paper.

OOP stands for Object-Oriented Programming. It's a programming paradigm that revolves around the concept of "objects," which can contain data in the form of fields (attributes or properties) and code in the form of procedures (methods or functions).

The key features of OOP in C++ include:

  1. Classes and Objects: Classes are user-defined data types that define properties and behaviors. Objects are instances of classes.
  2. Encapsulation: Encapsulation in C++ is a fundamental concept of Object-Oriented Programming (OOP) that involves bundling the data (variables) and methods (functions) that operate on the data into a single unit, called a class.
  3. Abstraction: Abstraction in C++ is the process of hiding the complex implementation details of a class or an object, and only exposing the essential features or behaviors that are relevant to the user. It allows the user to focus on what an object does rather than how it does it.
  4. Inheritance: Inheritance is a mechanism where a new class inherits properties and behaviors from an existing class. It promotes code reusability and enables the creation of a hierarchical class structure.
  5. Polymorphism: Polymorphism allows objects of different classes to respond differently to the same method call.
How's article quality?

Last updated on -

Page Contents