Structures and Namespace: Dr. Hadeer A. Hosny
Structures and Namespace: Dr. Hadeer A. Hosny
Structures and
namespace
Dr. Hadeer A. Hosny
Second term
2021
2 Points to be covered:
Structure
Introduction
Create a Structure
Initializing Structures
Assignment in structure variable
Comparing between structure variables
Structure and Functions
Pointer to Structure
Array of Structures
Nested Structures
Namespace
3 Introduction
C/C++ arrays allow you to define variables that combine
several data items of the same kind, but structure is another
user defined data type which allows you to combine data items
of different kinds.
Structures are used to represent a record, suppose you want to
keep track of your books in a library. You might want to track the
following attributes about each book −
• Title
• Author
• Subject
• Book ID
4 Introduction
A structure is a collection of variables of different data types
under a single name.
For Example : to store a student record which includes different
data items like (student_no, Fname, Lname, Total_Marks, GPA ,
…….).
#include <iostream>
#include <cstring>
using namespace std; Structure
struct Books { declaration
char title[50];
char author[50];
char subject[100];
int book_id;
};
int main() {
Initialize member
struct Books Book1; // Book1 of type Book of structure
struct Books Book2; // Book2 of type Book
// book 1 specification
strcpy( Book1.title, "Learn C++ Programming");
strcpy( Book1.author, "Chand Miyan");
strcpy( Book1.subject, "C++ Programming");
Book1.book_id = 6495407; Access to structure
// book 2 specification
strcpy( Book2.title, "Telecom Billing");
strcpy( Book2.author, "Yakit Singha");
strcpy( Book2.subject, "Telecom");
Book2.book_id = 6495700;
Structure
11
Following is the example to explain usage of structure
return 0;
}
Initializing Structures
12
Like normal variables Structure at the same time of
declaration.
Initialization of structure is almost similar to initializing
arrays.
Initializing Structures
13
Assignment in structure variable
14
Value of one struct variable can be assigned to another
struct variable of the same type using an assignment
statement.
Comparing between structure
15 variables
Solution is using
namespace
Namespace
29
A namespace is designed to overcome this difficulty and is used as
additional information to differentiate similar functions, classes,
variables etc. with the same name available in different libraries.
Defining a Namespace
A namespace definition begins with the keyword namespace
followed by the namespace name as follows −
namespace namespace_name {
// code declarations
}
#include <iostream>
using namespace std;
// first name space
namespace first_space { Output
void func() {
cout << "Inside first_space" << endl;
}
}
int main () {
cout << "std::endl is used with std!" <<
std::endl;
return 0;
}