3.
C++ programme to find length and width of box(private access specifier):
#include <iostream>
using namespace std;
class Box {
private:
double length, width; // Private members
public:
// Constructor to initialize the values
Box(double l, double w) {
length = l;
width = w;
}
// Getter functions to access private members
double getLength() {
return length;
}
double getWidth() {
return width;
}
};
int main() {
double l, w;
// Taking user input
cout << "Enter the length of the box: ";
cin >> l;
cout << "Enter the width of the box: ";
cin >> w;
// Creating an object of Box
Box myBox(l, w);
// Accessing private data using public getter functions
cout << "Length of the box: " << myBox.getLength() << endl;
cout << "Width of the box: " << myBox.getWidth() << endl;
return 0;
}
4.c++ programme to print width of box using protected accessed specifier:
#include <iostream>
using namespace std;
class Box {
protected:
double width; // Protected member
public:
Box(double w) : width(w) {} // Constructor
};
// Derived class to access the protected member
class DerivedBox : public Box {
public:
DerivedBox(double w) : Box(w) {}
void printWidth() {
cout << "Width of the box: " << width << endl;
}
};
int main() {
double w;
cout << "Enter the width of the box: ";
cin >> w;
DerivedBox myBox(w);
myBox.printWidth();
return 0;
}
5.c++ programming using three access specifiers
#include <iostream>
using namespace std;
class Example {
public:
int pubVar = 10;
private:
int priVar = 20;
protected:
int proVar = 30;
public:
void show() {
cout << "Public: " << pubVar << ", Private: " << priVar << ", Protected: "
<< proVar << endl;
}
};
class Derived : public Example {
public:
void showDerived() {
cout << "Public: " << pubVar << ", Protected: " << proVar << endl;
}
};
int main() {
Example obj;
obj.pubVar = 50; // Allowed
// obj.priVar = 60; // Not Allowed
// obj.proVar = 70; // Not Allowed
obj.show();
Derived d;
d.showDerived();
return 0;
}