Q:

Structure with private members in C++

belongs to collection: C++ programs on various topics

0

Example:

In this example, we are declaring a structure named "Student" which has two private data members rNo to store roll number of the student and perc to store a percentage of the student. And, to public member functions read() to read student details (roll number and percentage) of the student and print() to print the student details (roll number and percentage).

Public member functions read() and print() are accessing private data members rNo and perc just like a class. And the public member functions are calling within the main() function using the structure variable named std.

 

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program:

#include <iostream>
using namespace std;

//structure definition with private and public memebers
struct Student
{
    private:
        int rNo;
        float perc;
    public:
        //function to read details
        void read(void)
        {
            cout<<"Enter roll number: ";
            cin>>rNo;
            cout<<"Enter percentage: ";
            cin>>perc;
        }
        //function to print details
        void print(void)
        {
            cout<<endl;
            cout<<"Roll number: "<<rNo<<endl;
            cout<<"Pecentage: "<<perc<<"%"<<endl;
        }
};

//Main code
int main()
{
    //declaring structure variable
    struct Student std;
    //reading and printing student details
    //by calling public member functions of the structure
    std.read();
    std.print();
    
    return 0;
}

Output

 
Enter roll number: 101
Enter percentage: 84.02

Roll number: 101
Pecentage: 84.02%

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C++ programs on various topics

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Const Member Functions in C++... >>
<< Local Class with Example in C++...