Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
C++ program to hold student info using data hiding and encapsulation
Suppose we want to make student data type with data hiding and encapsulation. Students must have first_name, last_name, age and class items, but these variables cannot be accessible directly. We shall have to define some functions like get_firstname() set_firstname(), get_age() set_age() etc to retrieve and update variable values, and a to_string() function to display students details in this format (age, first_name, last_name, class). From the console take four parameters as input and set them using setter methods that we have defined, and show each items using getter methods and finally using to_string() method.
So, if the input is like
priyam kundu 16 10
then the output will be
16 priyam kundu 10 (16, priyam, kundu, 10)
To solve this, we will follow these steps −
define a class with first_name, last_name of type string and age, cl of type integer
define getter functions for all attributes
define setter functions for all attributes
define to_string() function using string-stream object and create formatted string that matches to the output format
From the main method do the following −
read each line and store first_name, last_name, age, cl respectively
call setter functions to set these values into the class members
print all attribute using getter methods;
display student info in this format (age, first_name, last_name, cl) using to_string() function.
Example
Let us see the following implementation to get better understanding −
#include <iostream>
#include <sstream>
using namespace std;
class Student{
private:
int age, cl;
string first_name, last_name;
public:
int get_age(){return age;}
int get_class(){return cl;}
string get_firstname(){return first_name;}
string get_lastname(){return last_name;}
void set_age(int a){age = a;}
void set_class(int c){cl = c;}
void set_firstname(string fn){first_name = fn;}
void set_lastname(string ln){last_name = ln;}
string to_string(){
stringstream ss;
ss << "(" << age << ", " << first_name << ", " << last_name << ", " << cl << ")";
return ss.str();
}
};
int main() {
Student stud;
int age, cl;
string first_name, last_name;
cin >> first_name >> last_name >> age >> cl;
stud.set_age(age);
stud.set_class(cl);
stud.set_firstname(first_name);
stud.set_lastname(last_name);
cout << stud.get_age() << endl;
cout << stud.get_firstname() << endl;
cout << stud.get_lastname() << endl;
cout << stud.get_class() << endl;
cout << endl << stud.to_string();
}
Input
priyam kundu 16 10
Output
16 priyam kundu 10 (16, priyam, kundu, 10)