SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Walter Savitch ,julia Lobur
Chapter:
Defining Classes
Exercise:
Self-test Exercises
Question:4 | ISBN:9780321531346 | Edition: 7

Question

Given the following struct definition:

struct A

{

int member_b;

int member_c;

};

declare x to have this structure type. Initialize the members of x member_b

and member_c, to the values 1 and 2, respectively.


Note: This requests an initialization, not an assignment of the members.

This distinction is important and will be made in the text in a later

chapter.

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

To declare a variable x of the struct A type and initialize its members member_b and member_c to the values 1 and 2 respectively, you can use the following C++ code is as:

PROGRAM CODE:

//Header file section
#include <iostream>
using namespace std;
//Structure class
struct A 
{
    int member_b;
    int member_c;
};

//Program starts a main program
int main() 
{
    // Declare a variable 'x' of type 'struct A'.
    A x;

    // Initialize members 'member_b' and 'member_c' with values 1 and 2 respectively.
    x.member_b = 1;
    x.member_c = 2;

    // Print the values of the members to verify the initialization.
    cout << "x.member_b: " << x.member_b << endl;
    cout << "x.member_c: " << x.member_c << endl;

    return 0;
}

OUTPUT:

x.member_b: 1
x.member_c: 2

 

0 0

Discussions

Post the discussion to improve the above solution.