First of all I would like you to recall the important thing that differentiates between C and C++ is OOP, Object Oriented Programming.
C++ is an Object Oriented Programming language. What do you mean when you say C++ is an Object Oriented Language. To understand this you should first know what OOP is. OOP as most of the beginner thinks is a programming language or some something that has feature known as Class, inheritance etc etc. Forget about everything else you know about OOP. Only remember,
1) It is a new way to program.
2) It is a way to program in such a way that we produce more robust and
more reusable code.
3) The above two points can be achieved by following the guide lines that OOP
suggests.
That’s it, no less no more. Now main features of OOP are,
1) Encapsulation
2) Abstraction
3) Inheritance
4) Function Overriding or also known as Runtime polymorphism.
All the features you will read in C++, e.g. Access Specifiers (Public, Private, Protected) or creating Classes etc. is there only to support above features.
From here I can take your question.
What are Access Specifiers? My life is simple why do I even need them? When to use? We need them because we want to follow a feature from OOP know as Abstraction.
Now, what is abstraction?
Abstraction means to show only the necessary details of the object(Assuming that you know what objects are and how are they created).
Do you know the inner details of the Monitor of your PC? What happen when you switch ON Monitor? Does this matter to you what is happening inside the Monitor? No Right, Important thing for you is weather Monitor is ON or NOT. Actually do don’t have to know. You need your computer just to get up and running when it is switched on. This is abstraction, which says hide that part of implementation which is not interesting for the user, which user don’t want to know. User only want to user the feature he don’t want to know how the hell is that implemented. So abstraction says expose only the details which are concern with the user. So the client who is using your class need not to be aware of the inner details like how you class do the operations? He needs to know just few details. This certainly helps in re-usability of the code.
How can we achieve above abstraction?
This is achieved by using access specifiers inside the class. Public, Protected and private are called access specifiers as they decide the access visibility of the function to the outside world.
A class can have multiple public, protected, or private labeled sections. Each section remains in effect until either another section label or the closing right brace of the class body is seen. The default access for members and classes is private.
class Base {
public:
// public members go here
protected:
// protected members go here
private:
// private members go here
};
The public members: A public member is accessible from anywhere outside the class but within a program. You can set and get the value of public variables without any member function as shown in the following example:
#include <iostream>
using namespace std;
class Line
{
public:
double length;
void setLength( double len );
double getLength( void );
};
// Member functions definitions
double Line::getLength(void)
{
return length ;
}
void Line::setLength( double len )
{
length = len;
}
// Main function for the program
int main( )
{
Line line;
// set line length
line.setLength(6.0);
cout << "Length of line : " << line.getLength() <<endl;
// set line length without member function
line.length = 10.0; // OK: because length is public
cout << "Length of line : " << line.length <<endl;
return 0;
}
When the above code is compiled and executed, it produces following result:
Length of line : 6
Length of line : 10
The private members:
A private member variable or function cannot be accessed, or even viewed from outside the class. Only the class and friend functions can access private members. By default all the members of a class would be private, for example in the following class width is a private member, which means until you label a member, it will be assumed a private member:
class Box
{
double width;
public:
double length;
void setWidth( double wid );
double getWidth( void );
};
Practically, we define data in private section and related functions in public section so that they can be called from outside of the class as shown in the following program. #include
using namespace std;
class Box
{
public:
double length;
void setWidth( double wid );
double getWidth( void );
private:
double width;
};
// Member functions definitions
double Box::getWidth(void)
{
return width ;
}
void Box::setWidth( double wid )
{
width = wid;
}
// Main function for the program
int main( )
{
Box box;
// set box length without member function
box.length = 10.0; // OK: because length is public
cout << "Length of box : " << box.length <<endl;
// set box width without member function
// box.width = 10.0; // Error: because width is private
box.setWidth(10.0); // Use member function to set it.
cout << "Width of box : " << box.getWidth() <<endl;
return 0;
}
When the above code is compiled and executed, it produces following result:
Length of box : 10
Width of box : 10
The protected members:
A protected member variable or function is very similar to a private member but it provided one additional benefit that they can be accessed in child classes which are called derived classes. You will learn derived classes and inheritance in next chapter. For now you can check following example where I have derived one child class SmallBox from a parent class Box. Following example is similar to above example and here width member will be accessible by any member function of it's derived class SmallBox.
using namespace std;
class Box
{
protected:
double width;
};
class SmallBox:Box // SmallBox is the derived class.
{
public:
void setSmallWidth( double wid );
double getSmallWidth( void );
};
// Member functions of child class
double SmallBox::getSmallWidth(void)
{
return width ;
}
void SmallBox::setSmallWidth( double wid )
{
width = wid;
}
// Main function for the program
int main( )
{
SmallBox box;
// set box width using member function
box.setSmallWidth(5.0);
cout << "Width of box : "<< box.getSmallWidth() << endl;
return 0;
}
When the above code is compiled and executed, it produces following result:
Width of box : 5
More examples and explanation, NOTE:- In all the examples below consider struct as class. May be you can just read struct as class. Consider the following struct:
struct DateStruct
{
int nMonth;
int nDay;
int nYear;
};
int main()
{
DateStruct sDate;
sDate.nMonth = 10;
sDate.nDay = 14;
sDate.nYear = 2020;
return 0;
}
In this program, we declare a DateStruct and then we directly access it’s members in order to initialize them. This works because all members of a struct are public members. Public members are members of a struct or class that can be accessed by any function in the program.
On the other hand, consider the following almost-identical class:
class Date
{
int m_nMonth;
int m_nDay;
int m_nYear;
};
int main()
{
Date cDate;
cDate.m_nMonth = 10;
cDate.m_nDay = 14;
cDate.m_nYear = 2020;
return 0;
}
If you were to compile this program, you would receive an error. This is because by default, all members of a class are private. Private members are members of a class that can only be accessed by other functions within the class. Because main() is not a member of the Date class, it does not have access to Date’s private members.
Although class members are private by default, we can make them public by using the public keyword:
class Date
{
public:
int m_nMonth; // public
int m_nDay; // public
int m_nYear; // public
};
int main()
{
Date cDate;
cDate.m_nMonth = 10; // okay because m_nMonth is public
cDate.m_nDay = 14; // okay because m_nDay is public
cDate.m_nYear = 2020; // okay because m_nYear is public
return 0;
}
Because Date’s members are now public, they can be accessed by main().
One of the primary differences between classes and structs is that classes can explicitly use access specifiers to restrict who can access members of a class. C++ provides 3 different access specifier keywords: public, private, and protected. We will discuss the protected access specifier when we cover inheritance.
Here is an example of a class that uses all three access specifiers:
class Access
{
int m_nA; // private by default
int GetA() { return m_nA; } // private by default
private:
int m_nB; // private
int GetB() { return m_nB; } // private
protected:
int m_nC; // protected
int GetC() { return m_nC; } // protected
public:
int m_nD; // public
int GetD() { return m_nD; } // public
};
int main()
{
Access cAccess;
cAccess.m_nD = 5; // okay because m_nD is public
std::cout << cAccess.GetD(); // okay because GetD() is public
cAccess.m_nA = 2; // WRONG because m_nA is private
std::cout << cAccess.GetB(); // WRONG because GetB() is private
return 0;
}
Each of the members “acquires” the access level of the previous access specifier. It is common convention to list private members first.
Why would you want to restrict access to class members? Oftentimes you want to declare members that are for “internal class use only”. For example, when writing a string class, it is common to declare a private member named m_nLength that holds the length of the string. If m_nLength were public, anybody could change the length of the string without changing the actual string! This could cause all sorts of bizarre problems. Consequently, the m_nLength is made private so that only functions within the String class can alter m_nLength.
The group of public members of a class are often referred to as a “public interface”. Because only public members can be accessed outside of the class, the public interface defines how programs using the class will interface with the class.
PLS NOTE:- They code used is not tested code so it may contains some errors. Since this is written at 2 :00 am it may contains grammatical mistakes.
PLS NOTE:- They code used is not tested code so it may contains some errors. Since this is written at 2 :00 am it may contains grammatical mistakes.
No comments:
Post a Comment