Protected
and private
are two access modifiers used to restrict the access of class members.
The private
access modifier restricts the access to the class members only within the same class. This means that only the class itself can access its own private members, and no other code outside the class can access or modify them. This is often used to keep the implementation details of a class hidden from other parts of the code.
The protected
access modifier is similar to private
, but it allows the members to be accessed within the class itself and any subclasses that inherit from the class. This means that the protected members can be accessed by the subclass and its instances, but not by any other code outside the class hierarchy.
#include <iostream>
using namespace std;
class Prim{
protected:
int height;
public:
string name;
int age;
void setName(string x) {
name = x;
}
void setAge(int y) {
age = y;
}
};
class Sec : public Prim {
public:
string job;
void setJob(string z) {
job = z;
}
void setHeight(int h) {
height = h;
}
void printAll() {
cout << "Name: " << name << endl;
cout << "Age: " << age << endl;
cout << "Job: " << job << endl;
cout << "Height: " << height << endl;
}
};
int main() {
Sec Object;
Object.setName("Michael");
Object.setAge(30);
Object.setJob("Canceler");
Object.setHeight(184);
Object.printAll();
return 0;
}
This code example demonstrate the usage of protected access specifier in inheritance.
In this code, there are two classes, Prim
and Sec
.
Sec
is inherited from Prim
using the public
access specifier. This means that all the public members of the base class will become public in the derived class, and all the protected members of the base class will become protected in the derived class.
The Prim
class has a protected
integer variable named height
, which is not accessible outside of the class but can be accessed within the class and its derived classes.
The Sec
class has a public string variable job
and three member functions - setJob()
, setHeight()
, and printAll()
. The setJob()
function sets the job of the object, the setHeight()
function sets the height of the object, and the printAll()
function prints all the details of the object.
The printAll()
function also accesses the height
variable, which is a protected member of the Prim
class. This is possible because Sec
is a derived class of Prim
, and height
is a protected member of Prim
, so it can be accessed within the derived class.
In the main()
function, an object of the Sec
class is created, and its various member functions are called to set its attributes and display its details.
No comments:
Post a Comment