Access Modifiers/Specifiers
Posted on November 17, 2022 • 2 minutes • 384 words
Types Of Access Specifiers
- Public
- Private
- Protected
Related videos
1. Public
public members can be access from any part of the program.
class Rectangle
{
public:
Rectangle()
{
length = 0;
width = 0;
}
Rectangle(double l, double w)
{
length = l;
width = w;
}
double getArea()
{
return length * width;
}
double length, width;
};
int main(int argc, char const *argv[])
{
Rectangle r1(10,20);
std::cout << "length :" << r1.length << std::endl;
std::cout << "width :" << r1.width << std::endl;
std::cout << "area :" << r1.getArea() << std::endl;
return 0;
}
2. Private
-
private members can be only accessed from within the class.
-
Also
friend class
andfriend functon
can access it.
class Rectangle
{
public:
Rectangle()
{
length = 0;
width = 0;
}
Rectangle(double l, double w)
{
length = l;
width = w;
}
double getArea()
{
// private members only access from within the class.
return length * width;
}
private:
double length, width;
};
int main(int argc, char const *argv[])
{
Rectangle r1(10,20);
// private members can not access from out side of the class
//std::cout << "length :" << r1.length << std::endl;
//std::cout << "width :" << r1.width << std::endl;
std::cout << "area :" << r1.getArea() << std::endl;
return 0;
}
3. Protected
-
protected members can be accessed from within the class.
-
Also from the
child class
.
class Rectangle
{
public:
Rectangle()
{
length = 0;
width = 0;
}
Rectangle(double l, double w)
{
length = l;
width = w;
}
double getArea()
{
// protected members can access from within the class.
return length * width;
}
protected:
double length, width;
};
// child class of Rectangle
class Square : public Rectangle
{
public:
Square(double l)
{
// protected members can access from the child class.
length = l;
width = l;
}
double getSquareArea()
{
// protected members can access from the child class.
return length * width;
}
};
int main(int argc, char const *argv[])
{
Rectangle r1(10,20);
// protected members can not access from out side of the class
//std::cout << "length :" << r1.length << std::endl;
//std::cout << "width :" << r1.width << std::endl;
std::cout << "area :" << r1.getArea() << std::endl;
Square s(10);
std::cout << "Square Area : " << s.getArea() << std::endl;
return 0;
}