on Leave a Comment

C++ Structures Concepts

Structure is a group of dissimilar elements. Structure is used to create new data type. In C++, structure and class are similar, but there is a minor difference between structure and class. Structure is a collection of variables of either similar or dissimilar data type.

Suppose, you have to store information about book. This information consists of book_title and book-price. Now these data cannot be store in a single variable. But, if you create multiple variables to store book_title and book_price for particular book, then problem of data accessing for particular book will be arise. To solve this problem, both class and structure can be used. But today I will discuss only about structure in C++.

Defining structure in C++ programming

The struct keyword is used to define structure in c++ programming. A structure can be define locally or globally in a program. 

If structure is defined inside a function, then structure cannot be accessed outside that function. 

If structure is defined outside all functions, at the beginning of program, then structure can be accessed in all functions.

Syntax for defining structure in C++ programming

struct <structure-tag>
{
    <data-type> <variable 1>;
    <data-type> <variable 2>;
    ..........
    <data-type> <variable n>;
}[structure variables];

Example:

struct book
{
   float book-price;
   char book_title[20];
}b1;


Here, book_price and book_title are public members of structure book.  

Accessing structure members in C++

Accessing method of structure members in C++ is similar to C language. The dot (.) operator is used to access structure members.

Example:

struct book
{
   float book-price;
   char book_title[20];
}b1;

Here, book is a user-defined data type and b1 is a variable of book data type. If you want to access book_price and book tittle of variable b1.

Then you will write,
b1.book_price;
b1.book_title;

Program to access structure members in C++

#include<iostream>
#include<string.h>
using namespace std;
struct book
{
   float book-price;
   char book_title[20];
};
int main()
{
    book b1;
    b1.book_price=245.78;
    strcpy(b1.book_title,"C++ programming");
    cout<<b1.book_price;
    cout<<endl;
    cout<<b1.book_title;
    return 0;
}

OUTPUT:

245.78
C++ programming

Here, dot operator is used to access structure members.

You cannot write b1.book_title="C++ programming" instead of strcpy(b1.book_title,"C++ programming"). Because b1.book_title means the address of first block of array title. Address is a constant and constant cannot be written on the left hand side of assignment operator.

0 comments:

Post a Comment