Home » C++ programs » C++ Class and Objects programs

Structure with private members in C++

C++ | Structure with private members: Here, we are going to learn private members of the structure in C++ programming with an example?
Submitted by IncludeHelp, on September 19, 2018

As we know that by default, structures members are public by nature and they can be accessed anywhere using structure variable name.

Sometimes a question arose "Can a structure has private members?"

The answer is "Yes! In C++, we can declare private members in the structure". So the important thing is that "we can declare a structure just like a class with private and public members".


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.


#include <iostream>
using namespace std;

//structure definition with private and public memebers
struct Student
        int rNo;
        float perc;
        //function to read details
        void read(void)
            cout<<"Enter roll number: ";
            cout<<"Enter percentage: ";
        //function to print details
        void print(void)
            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;
    return 0;


Enter roll number: 101
Enter percentage: 84.02

Roll number: 101
Pecentage: 84.02%


Comments and Discussions



Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© some rights reserved.