in C++, TCPPPL

TCPPPL Chapt 7 : Pointers

As a former C programmer (as a student), this seems to be a familiar topic to me : really, the only thing you need to learn about C is pointers. However, people like me need to be aware of certain things.

void *. The book mentions that void * must be explicitly converted before it is assigned to a certain pointer type. I can’t remember that if you can use it without cast in C. Anyway, this is the reason why nullptr is better than NULL, according to the book. ( NULL may be macro of (void *)0 ). read more

TCPPPL Chpt6: ISO C++ Standards

Apparently this chapter is like a law book. I will left this as a list and I will finish this later when I finish this book.

  • Implement defined features, unspecific, and undefined
  • Hosted vs Freestanding implementation
  • Source character set
  • int/pointer to bool
  • char impl defined signed/unsigned : ok to convert to unsign ed
  • int{c} construct int from a char
  • 3digit octal
  • multicharacter literal
  • Unicode
  • int –
  • prefix and suffix, user defined literals
  • constexpr in <limits>
  • <cstdint> for int with variance needs
  • alignof
  • declaration and definationm,
  • scope: refer to global and self init
  • {} in declaration
  • missing initializers
  • () and function
  • auto
  • decltype
  • lvalue and object, and rvalue
  • objects lifetime
  • read more

    Basic of C++: A tour

    It is very interesting for a language book to have a quick tour before everything. Actually, it is a great idea for people whose first language is not C++. People just don’t have to go through the basic things like control flows to know a language.

    Generally, I have a feeling that C++’s code explain more itself. Programmers know more about what they are doing instead of checking documents for reference.

    The Basics

    Chapter 2 covers the very basic things (that would include control flows). First thing to note is that the introducing of namespace. Namespace in C++ seems to be clear and straightforward. What is not-so-straightforward is the name of header file/shared object library. Well, Java’s package infrastructure makes things more clear, though trying to put everything inside its structure probably is not so clever.

    I didn’t expect C++ provides things like ‘auto’. (Well, not the ‘auto’ when I first use C language a few years ago.) Anyway, C++ is not a dynamic tool language. However, if you think about it, it is nothing runtime here, and you just need a compile time check. To be a real dynamic language, the thing you need is a flexible variable type (which is implemented in runtime even if you could do it in compile time) and generic programming for functions.

    We finally have bools in C++!

    C already have const. It was a beautiful promise that one should keep. constexpr does more than that. It calculates the value at compile time. When using constexpr as decorator of a function, it will evaluate at compile time when possible. Those function must be as simple as only having a return statement. Note that if a value is const, the compiler will assume you to keep the promise. Conclusion: Do keep your promise or you will have something unexpected.

    Structs are improved. Say goodbye to the strange typedef!

    Operators are functions, which they should be! Just need to have it in mind that if the value is lvalue or rvalue, to make the return type reference when necessary.

    We also got a good syntax sugar for initiating fields. And a real enum class which is more than int.

    C++ provides a more standard way for error handling. Exception introduced just like all of the other modern programming languages. Static assertions provide error handling on compile time.

    There are some designing ideas. Invariant are restrictions applied to class definitions, and should be present in the code. If not, the functions should be independent rather than a member.

    Abstract mechanism

    As we can find in any articles about OOP, there is some mechanism in classes, like concrete/abstract class and class. There are some concerns under data storage since in C family you have to care more about memory, like the idea of the container. Also, note the following format for heap allocated arrays.

    double *elem = new double[s];
    delete[] elem;

    Instead of making all functions virtual, we need to explicitly specify if a function is a virtual one. A class with at least a virtual function is called abstract class, which can not be instantiated. The mechanism behind overriding is vtbl. Usually, this is to add a 4 byte for pointer at the beginning of each object. If we want to call the virtual function in the base class, we can use scope resolution (::) operator to specify the class name, and this is called suppressed.

    Constructor and destructor are called in a certain order. We don’t need to do anything for the constructor. However, for destructors, we need to make them virtual on base classes. Otherwise, only one of them is called.

    An important designing idea for C++ is cautious against pointers. In C code, it is not strange for a function to return a raw pointer which points to something in heap. However, it is no longer recommended in C++. Destructors help us manage heap memory more freely. Moreover, we have unique_ptr as a smart pointer.

    We need to note that “this” is a pointer, as it is in Java. Also, a const method is one that doesn’t change the object. Moreover, we can specify access-specifier when inheriting.

    Copy and move. The default behavior of C++ copy is shallow copy since it just does a copy bitwise. To make it copy deeply, we just need to override operator =. Moreover, C++ provides the std::move mechanism.

    std::move is a fast way to generate “right value reference”. In many cases, we don’t really need to copy the whole objects, especially when it is a container( such that copy is expensive. )  && is the mark for right value reference. When it is a parameter of a function, it (instead of the const &) can match the right value reference, to do a memory-economic behavior in the function.

    If we don’t want certain behavior in the derived class, we can use the “=delete” mechanism.

    class Shape{
        //no copy
        Shape(const Shape&)=delete;
        Shape& operator=(const Shape&)=delete;
        //no move
        Shape(Shape &&)=delete;
        Shape& operator=(Shape &&)=delete;

    Template. Generic programming is very useful for OOP. C++ has the template grammar:


    template<typename T>


    template<typename T, typename U>


    template<typename T, typename... Tail>
    void f(T head, Tail... tail){

    To override the operator(), we can use it as a functional object. For instance

    <typename T> class Less_than{ const T val; public: Less_than(const T &v): val(v){} bool operator()(const T &v) const {return v<val;} } read more

    Enough for Java. Let’s look at something new with C++

    Java is a good tool. It arranges everything for you and you don’t have to worry about the details. For those who do want to know about the details, it is interesting to dig a little bit into it. However, perhaps I don’t have time for it now.

    I tried Visual Basic when I was in middle school, but I didn’t really do anything nontrivial with it. Thanks to the university I attended for undergraduate courses, my first serious programming language was C. I am proud of this fact since in C you can handle many things in the hardware or OS level. You don’t have many shortcuts, which means you have to build it with your hand. That gave me much freedom to play with pointers to do things I could never imagine when I had to switch to Java when I was a Master student.

    I am happy to work with C++ now. C++ is not C with pointers, at least for Bjarne Stroustrup. I was surprised that he didn’t recommend pointer arithmetics and malloc for heap memories, which was very fun when I write C. After all, probably no one likes C++ in C styles. I will go check what C++ has for me. Heh.

    mockable-24-android.jar : Sometime too large

    As a TA of the course “Mobile Application App”, I recently run into a problem. The teacher asks students to upload their homework to LATTE, our university’s course management platform. However, the size limit of LATTE platform is 20 MB, and



    As Professor Chaturvadi suggests that we’d better stick on Latte for homework submission, I tried to load the apk. Actually, it does work on my AVD. But the thing is, although apk is actually zip, many files are turned into binary. Android Studio 2.2, which is released on 9/19, has a tool to decompile the code. However, I bet none of us want to read decompiled code like this:

    If we want to stick on LATTE, we can definitely ask students to remove $rootDir/build/mockable-android-24.jar. The conclusion comes from Android Studio’s document regarding their new build system: read more

    TIJ chapter 8: Polymorphism

    Polymorphism(also called dynamic binding or late binding or run-time binding) is an essential concept in OOP. This chapter is basically a more detailed explanation of polymorphism, which is highly relevant to inheritance. (As mentioned in chapter 7, in many cases inheritance is meaningless when polymorphism is not necessary.)

    Binding method

    How Java find a corresponding method for an object? Unlike languages like C, which use early binding for each function, Java only does early binding for methods with modifiers like static or final. Java has runtime binding for other methods. That’s the reason why people declare methods “final” in the early versions of Java to improve performance.

    Runtime binding helps the compiler to refer to an override method to the correct derived class, even if we only know a base-class reference to an object. We can construct special cases where even programmer doesn’t know what kind of derived class an object belongs to, but finally, the compiler will figure out it during the runtime. During runtime, the compiler binds correct binary.

    Dynamic dispatch is a fundamental feature of OOP. Java does this for each method, while C++ only enable it for virtual functions.


    In this way, the behavior won’t change even if we add new methods for based classes and derived classes, or we add a new derived class. OOP provides extensibility to programming.


    For private methods in a base class, even if you have a public method with the same signature in a derived class, you will call the private one in the base class for a base class reference. It won’t throw an exception, so this should be noticed.

    Another thing to note is dynamic binding is only for methods, not field. But if we set each field private and use getters and setters, this shouldn’t be a problem.

    Constructor, Destructor, and Polymorphism

    The constructor is a static method. When the constructor is called, the calling order is from base to derived. If we have to build a destructor, we will make it reverse, from derived to base.

    How about calling overload method in the constructor of the base class?

    When the constructor of the base class, method successfully refer to the derived one. However, the derived-related field has not been initialized. So the value printed is neither 1 nor 5. In fact, it is 0.

    Memory space is initialized to 0 for objects, and that’s why we get 0 as output. To avoid this, the programmer should think twice before she/he call a method in a constructor. Only final methods (include private ones) are safe to be called in the constructor.


    Sometimes we need to downcast an object to call methods only in derived class. Java will check if the downcasting is safe. If not, it will throw a ClassCastException.




    TIJ chapter 7: Reusing Classess

    Composition, inheritance and delegation are 3 main methods to reuse classes.

    Delegation is not a familiar concept for me, and it is not directly supported. However, I think I have used its content before. It just put a member object in the new class and expose all method to the new one.

    About inheritance, it always calls the super() constructor even if you don’t called it literally in derived class. As a result, if the base class don’t have a constructor without any parameters, and you don’t call base class constructor literally in derived class, you will get a compile time error.

    Upcasting is brought by inheritance. Basically, it means a reference of base class can refer to an instance of derived class. Making good use of this feature help DRY. In some cases, whether using inheritance depends on if upcasting is necessary.

    About Final

    “Final” usually means “unchangeable”.

    If a data is final, then it can either initialize in compile time or run time, and cannot be changed since then. If it is static and final, it has only one piece of storage that cannot be changed.

    For non-static final, it can be left blank when declaration, but then must be decided in constructor. In conclusion, a final field must be assigned either with an expression at definition of the field or in every constructor. Of course, if it is static, assignment in constructor is also impossible.

    If a reference is final, then it cannot refer to another Object. The object itself can also be changed. You cannot make object unchangeable by using final.

    If a parameter of a method is final, it cannot be changed in method. It is usually used to transfer data to anonymous inner class.

    Making a method final is to prevent derived class change it. Historically, it may also improve the efficiency, but now this purpose is less useful.

    As a result, a private method implies final. People can add final modifier to private method, but it is meaningless. Note that in derived class, you can define method with same name and parameter types, but it is NOT overriding, since private methods are totally invisible in derived class.

    If a class is final, it cannot have any derived class.

    Expecting a method to be final means it cannot be override. However, your expectation may not be reasonable. An example is Vector class in previous version of Java. Final methods make late implement of Collections use ArrayList instead.

    At the end of this captor, it emphasize again that statics are initialized at the first use of the class, it can be when the first object of that class (includes derived class) is constructed, or when a static field or static method is accessed.

    TIJ chapter 6: Access Control

    This chapter is not a complex one. It just tells the access control involved in Java.

    There are 4 access level in Java, public,  protected, package-private, private. (By accident they all start with letter “p”). Package-private is the default one without any modifier. The only thing one should note is the protected access level implies package-private ones(Actually this is true for all 4 levels, one implies the other one by order).

    If one doesn’t allocate a package for a class, this class will belong to the default package. Default package in a same directory is viewed as one package.

    People can make use of the access control to reach certain “design patterns”(which is in derision by C programmers). For instance, to create a class that only one instance is available.

    TIJ chapter 5: Initialization and Cleanup

    This chapter is really the beginning of OOP. I think Java is really designed with the concept of OOP. Even those process oriented programming elements are forced to be absorbed in that systems and become static element. If in one day, which may not be too far away, OOP are no longer popular, Java would either.

    Ironically, we always had to have some place to start up a program, and that place can’t be an non-static method, at which no object has been created since it is the beginning. So, the starting point is always a static method, either main() method or something else in JUnit or things like that. In that static method, we can call other static methods or create new objects and run non-static method on that. However, every static method cannot go beyond classes.

    Yesterday, one of my friends asked me questions about calling a method in another methods. I hadn’t think into this problem systemically, and hence I summarized all situations: in a static method, you can call other static methods in same class and omit class name, call other classes’s static methods, and call non-static methods via objectname.method; in a non-static method, in additional to the above, you can also call method of this object omitting “this.”. My friend said that the reason he was confused is that an omitted prefix can be either “classname.” or “this.”. I told him, force POP into Java’s OOP system as static fields is what the problem is.

    According to the book, how non-static method works is Java inwardly take the object as an additional parameter of the method. Actually, python also do this, but in public: first parameter must be “self ” in this case.

    And it also solved a doubt: why some method return this, since this should be known when called; in this case, multiple operations can be operated in one line.

    “this” has another use: use this(paras…) as constructor in other overloading constructors, but only once at the beginning of other constructor, and must be at the very beginning, like “super”.

    It is not a surprise that we cannot expect finalize() to run since people don’t know when garbage collection work. The book point out that two situations where finalize() is needed: one is when you are using JNI since C/C++ don’t have GC systems. The other is to verify the ending condition.

    Other parts of the class is about initialization. Basically, programmers must manually initialize local variables. For fields, things are more flexible. It has a default value. Also, the value can be set by programmer. Basically, those initialization is by order, which means methods which has been defined can be called. However, even if fields are separated by methods, all of them will be initialize. When a class have static fields and blocks, they will always be initialized first when the containing class are referred, either static or non-static. However, those initializations only run one time. Then, every time an instance are created, non-static fields and blocks will be initialized. After that, the constructor runs.

    SSL certification deployed

    Today I deployed SSL certification on my blog. As a result, my blog is only available from HTTPS, and all attempting from HTTP will be redirected to HTTPS. To do this, just add this to the Apache2 available sites configuration, like this:

    A small vignette is that they give me a mismatch cert after I receive this message from Namecheap. Apache refused to restart, then. So, I had to ask them to reissue my cert.

    Basically, Aleph Zero(\aleph_0) is the cardinality of the natural numbers. A set with a cardinality of Aleph Zero means the number of elements is “as many as natural number”, which is “the smallest infinity”. It might be hard for a computer to understand infinity, we human beings can, though.

    Update: Someone make his hostname point to my site via HTTP, and is then also 302 redirected to my HTTPS site. It has been blocked.

    Update: Starting from June 8, 2016, GitHub Page supports HTTPS, so I updated my GitHub Page to HTTPS too. I heard that chrome will mark those sites who still use HTTP “not secure” soon.