Sunday, 14 July 2013

Access Specifiers. What are they, why are they needed and where are they?

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. 

Sunday, 2 June 2013

Mutable keyword and its relation with const

This will cover basic concept, Mutable and its relation with const. Though it is basic concept and almost all of us know about it yet many programmers tend to use it in a wrong way. So here we go,

Mutable

The keyword mutable is used to allow a particular data member of const object to be modified. This is particularly useful if most of the members should be constant but a few need to be updateable. Suppose we add a "salary" member to our Employee class. While the employee name and id may be constant, salary should not be. Here is our updated class.    
class Employee {
public:
    Employee(string name = "No Name", 
        string id = "000-00-0000",
        double salary = 0)
    : _name(name), _id(id)
    {
        _salary = salary;
    }
    string getName() const {return _name;}
    void setName(string name) {_name = name;}
    string getid() const {return _id;}
    void setid(string id) {_id = id;}
    double getSalary() const {return _salary;}
    void setSalary(double salary) {_salary = salary;}
    void promote(double salary) const {_salary = salary;}
private:
    string _name;
    string _id;
    mutable double _salary;
};
Now, even for a const Employee object, the salary may be modified.
const Employee john("JOHN","007",5000.0);
....
....
john.promote(20000.0);

I've seen this sort of terrible idea before. This sort of madness leads to flawed code and defeats the entire purpose of const in C++. I can only conclude that the people writing this sort of nonsense themselves don't understand the purpose of mutable. So they teach a mistake, passing on this nonsense to the next group of C++ programmers who pass it on themselves. This must stop.
When you mark a variable const, you are promising (and asking C++ to enforce) that you will never logically modify the contents of that object. Perhaps the most useful reason to do this is when you pass an object into a function by reference or pointer. By making it const, the function promises to not mess with your object. For example, say you have a class Robot that inherits from Person. You want to pass your Robot into the function take_pulse. You want take_pulse to use Robot's overridden methods, so take_pulse takes the object by reference. Because it's const, you can be confident that take_pulse won't modify the Robot, just read from it:
class Person {
public:
    virtual bool has_pulse() const { return true; } 
    void set_name() { /* ... */ }
};

class Robot : public Person {
public:
    virtual bool has_pulse() const { return false; }
    void set_name() { /* ... */ }
};

/*
Because Person is const, take_pulse cannot call set_name().
Because Person is a reference, we can pass in a Robot robot
and get the correct answer (false).
*/
bool take_pulse( const Person & X ) {
    return X.has_pulse();
}
It's nonsense to make the salary mutable; you're just making it possible for code that gets a constant object to mess with the salary. If the employee is constant, you shouldn't be messing with his salary.
So what if you want the employee's name and id to be constant, but not the salary? Well, just say so!
class Employee {
public:
    Employee(string name = "No Name",
        string id = "000-00-0000",
        double salary = 0)
    : _name(name), _id(id)
    {
        _salary = salary;
    }
    string getName() const {return _name;}
    string getid() const {return _id;}
    double getSalary() const {return _salary;}
    void setSalary(double salary) {_salary = salary;}
    void promote(double salary) {_salary = salary;}
private:
    const string _name;
    const string _id;
    double _salary;
};
Now they're constant. Of course, this means you can only set them in the constructor.
So if the above madness isn't what mutable is for, what is it for? Here's the subtle case: mutable is for the case where an object is logicallyconstant, but in practice needs to change. These cases are few and far between, but they exist.
Here's one example: You have a constant object, but for debugging purposes want to track how often a constant method is called on it. Logically you're not changing the object. Note that if you're making decisions in your program based on a mutable variable, you've almost certainly violated logical constness and need to rethink things.
class Employee {
public:
    Employee(const std::string & name) 
        : _name(name), _access_count(0) { }
    void set_name(const std::string & name) {
        _name = name;
    }
    std::string get_name() const {
        _access_count++;
        return _name;
    }
    int get_access_count() const { return _access_count; }

private:
    std::string _name;
    mutable int _access_count;
};
As a more complex example, you might want to cache the results of an expensive operation:
class MathObject {
public:
    MathObject() : pi_cached(false) { }
    double pi() const {
        if( ! pi_cached ) {
            /* This is an insanely slow way to calculate pi. */
            pi = 4;
            for(long step = 3; step < 1000000000; step += 4) {
                pi += ((-4.0/(double)step) + (4.0/((double)step+2)));
            }
            pi_cached = true;
        }
        return pi;
    }
private:
    mutable bool pi_cached;
    mutable double pi;
};
Now we don't calculate pi until someone asks for it, but when they do we cache the result, which is good because we're calculating it in a really slow and stupid way. Logically the function is still const (pi isn't about to change).
Ultimately you almost certainly do not need mutable at any given moment. I've gone years between wanting the mutable keyword. If you think you need mutable, think twice. Be sure that the object will still be logically constant, even as its internals change. 

Please write to me to point some missing areas or mistake. also kindly pardon me for improper formatting.


Sunday, 26 May 2013

Regarding blog and its plans.

Date:- 30-10-13
Guys could not really add much in  memory management stuff, actually it took much longer time than I expected. I still have many doubts on this topic. Some topics are,
- How memory is managed in Windows these days. I can't find any to the point answers anywhere, probably there is fault in my Google strings. I also referred Mark R's videos on channel 9 but I don't think it gives detailed information of how everything is managed or may be a I need more clarity on more basic stuff but whatever I need more studies around this topics.
Btw, I am reading templates from Thinking in C++ vol2. Read few pages and does not feel like as if I am reading some fancy literature book. Very nice and easy to understand book. 

Date:- 20-10-13
Sincere, apologies that I am not able to cover the C++11 topic but I will be doing it soon before December 2013 ends.
Right now I am focusing more on OS side so my coming notes would probably be on OS, particularly Memory Management. Please feel free to ask any question or add any point if you have.
during Diwali I will cover Templates but I will not post any notes on that topic. Though I welcome all questions.

Meanwhile, here is really nice link you can go through,http://www.codeproject.com/Articles/570638/Ten-Cplusplus11-Features-Every-Cplusplus-Developer


Date:- 26-5-13
I am starting this blog with the intention to share programming knowledge and discuss on various programming topics. I will start with some very basic topics.One mile stone for this blog, for now, would be covering C++11.

Since I am new I will not be able to update/post very actively. Here we will surf the areas of  C/C++/python...

Note:- These posts written by me may also contain the data, completely or partially, from other sources as well so there are scope of mistakes or redundancy so please feel free to reply to me directly or write to the posts if you find something.

------------------------------------------------------------------------------------------------------------
Operating system lectures ;- http://web.cs.wpi.edu/~cs3013/c07/