cpp Encapsulation
Published on: 04 February 2025
Resources
Aim: Write a program that showcases the application of Encapsulation.
Practice Exercise 8: Write a program that showcases the application of Encapsulation.
Theory:
The program defines a Material class that represents materials with their names and densities. It includes private data members for encapsulation and public member functions for access and modification. The constructor initializes material properties, while getter and setter functions allow retrieving and updating values. In the main function, two Material objects (steel and aluminum) are created and their properties are displayed. Later, the density of steel and the name of aluminum are modified, demonstrating encapsulation and object manipulation in C++.
Algorithm:
- Define a
Material
class with private members:name
anddensity
. - Implement a constructor to initialize
name
anddensity
. - Provide getter functions to retrieve material properties.
- Provide setter functions to modify material properties.
- In
main
, create twoMaterial
objects with initial values. - Display the name and density of each material.
- Modify
steel
's density andaluminum
's name using setter functions. - Display the updated properties.
- End the program.
Code:
#include <iostream>
using namespace std;
class Material
{
private:
string name;
double density;
public:
Material(string n, double d)
{
name = n;
density = d;
}
string getName()
{
return name;
}
double getDensity()
{
return density;
}
void setName(string n)
{
name = n;
}
void setDensity(double d)
{
density = d;
}
};
int main()
{
Material steel("Steel", 7.85);
Material aluminum("Aluminum", 2.70);
cout << "The density of " << steel.getName() << " is " << steel.getDensity() << " g/cm^3." << endl;
cout << "The density of " << aluminum.getName() << " is " << aluminum.getDensity() << " g/cm^3." << endl;
steel.setDensity(7.90);
aluminum.setName("Aluminum Alloy");
cout << "The new density of " << steel.getName() << " is " << steel.getDensity() << " g/cm^3." << endl;
cout << "The new name of the material is " << aluminum.getName() << "." << endl;
return 0;
}
References
There may be some AI Generated content in this article used for demonstration purposes.