Lesson Learned [23/07/2014]

1. File Open - fpopen usage

To use the fopen,the most important part is that you have to pass in a char *filename and the mode has to be a char *mode. A common mistake is to use a char instead, eg. 'r'.

Incorrect :
 key_file_descriptor_ = fopen(file_name_,'r'); 

 Correct :
 key_file_descriptor_ = fopen(file_name_,"r"); 


2. Const Member Function in Static Function not allowed (eg. void ClassA::FuncA(int number) const

To be static, it means that this function is not bounded to any object of this class, which mean that kind of being shared by all objects of the class. This mean that there is no concept of const function which do not change the state of an object to speak of.

Incorrect:
 void static MyClassA::Func(int number) const;


3. Enum in Classes

Before C++11, the very confusing factor is enum are global and by that with the help of namespace and classes, we can restrict it to the namespace::class scope. However, within it, all elements of the enum becomes global. This mean that you cannot do this.

Incorrect:
class MyClass{
    public:
           enum kHTTPMethods {GET,PUT,POST}
};
void MyClass::Func(){
    kHTTPMethods method = kHTTPMethod.GET;
    //The reason is . operator can only be use 
    //on objects (instances) of a class
}
Correct:
void MyClass::Func(){
    kHTTPMethods method = GET;
    //Because all elements of the enum becomes scope to the class, 
    //you can use this.
}
or
void MyClass::Func(){
    kHTTPMethods method = MyClass::GET 
    //Correct but redundant
    //Once again, because the enun is in scope within the class
}
In C++11, there is an introduction of the enum class, which changes the class declaration to the following:
class MyClass{
 public:
        enum class kHTTPMethods {GET,PUT,POST}
        enum class kFTPMethod{GET,SEND}  
        //Previously, GET cannot be repeated 
        //because they clash in the namespace
};
You must scope further to the enum class, which is actually a great improvement.
void MyClass::Func(){
    kHTTPMethods method = kHTTPMethods::GET 
    //It must be scoped further to the enum class
}

Comments

Popular Posts