Showing posts with label CPP. Show all posts
Showing posts with label CPP. Show all posts

Thursday, 4 February 2016

Model View Control (MVC) pattern usage in C++

MVC (Model-View-Controller) pattern is often used in Web based applications, where "View" is your actual HTML content displayed on browser, where as "Controller" is the code that gather dynamic data and generates content within the HTML. Finally, "Model" talks about actual content, probably stored in DataBase or XML, and your business rules transform these contents based on user actions.
As I mentioned, MVC is most widely used in web based applications, but some how I liked this pattern and tried using it in my C++ application.
Scenario is, I have a module in C++ which generates set of System Information, and displays them to user. Since, they are system information, they keep change, and I have to update at view the same. Hope you understood.

Since I cannot get you what I wrote in my module, but I can surely show you a sample code, (the code is simple and self explanatory)

/* * * * * * * * * * * * * * *
* File       : mvc-class.cpp
* Author     : Kiran Puranik
* Copyrights : no copy rights :)
*
* * * * * * * * * * * * * * */

#include <iostream>

using namespace std;

/* Model class */
class SystemInfoModel {
   
private:
    string m_InfoName;
    string m_InfoValue;
   
public:
    string Get_InfoName (void) {
        return m_InfoName;
    }
   
    string Get_InfoValue (void) {
        return m_InfoValue;
    }
   
    void Set_InfoName (string info_name) {
        if (!info_name.empty()) {
            m_InfoName = info_name;
        }
    }
   
    void Set_InfoValue (string info_val) {
        if (!info_val.empty()) {
            m_InfoValue = info_val;
        }
    }
};

/* View class */
class SystemInfoView {

public:
    void Print_SystemInfo (string name, string val) {
        cout << "|---------------------------------|" << endl;
        cout << "|    System Info    |    Value    |" << endl;
        cout << "|---------------------------------|" << endl;
        cout << "|   " << name << "    |   " << val << "   |" << endl;
    }
};

/* Controller class*/
class SystemInfoController {

private:
    SystemInfoModel m_SysModel; //\ reference for Model and View
    SystemInfoView  m_SysView;  ///
   
public:
    /* CTR */
    SystemInfoController (SystemInfoModel si_model, SystemInfoView si_view) {
        m_SysModel = si_model;
        m_SysView  = si_view;
    }
   
    /* User control APIs */
    void Set_SystemInfo_Name (string si_name) {
        if (!si_name.empty()) {
            m_SysModel.Set_InfoName (si_name);
        }
    }
   
    void Set_SystemInfo_Value (string si_val) {
        if (!si_val.empty()) {
            m_SysModel.Set_InfoValue (si_val);
        }
    }
   
    string Get_SystemInfo_Name (void) {
        return m_SysModel.Get_InfoName();
    }
   
    string Get_SystemInfo_Value (void) {
        return m_SysModel.Get_InfoValue();
    }
   
    /* Now, bind the Model with View */
    void Update_System_Info (void) {
        m_SysView.Print_SystemInfo (m_SysModel.Get_InfoName(), m_SysModel.Get_InfoValue());
    }
};

/* Now, usage part of it ----------- */
int main ()
{
    // system info model instatiation
    SystemInfoModel siModel;
    siModel.Set_InfoName ("Memory Usage"); // looks dirty isn't it. But usually they are
    siModel.Set_InfoValue ("1024 KB");   //
fetched from system units/or other utilities
   
    // system info view instatiation
    SystemInfoView  siView;
   
    // now, the controller
    SystemInfoController siControl (siModel, siView);
   
    // let's display the content now
    siControl.Update_System_Info ();
   
    // now, the system info has changed, value is different
    siControl.Set_SystemInfo_Value ("2048 KB");
   
    // and display updated content
    siControl.Update_System_Info ();
   
    // isn't it a great pattern !!!!
   
    return 0;
}



Tuesday, 23 April 2013

Why C++ compilation takes more time

C++ is one of the strong programming language, I believe. But people complain saying it takes long time to compile even a small piece of code compare to other competitors like C# or Java. The answer is Yes. 
Straight away we can think of one basic reason for this, the pre-processor directives, which gives instructions to compiler to pre-process the information before the actual compilation starts, and I should not miss, #include is also one among that pre-processor directives. But in reality, this is not only the reason. I was going through the whole compilation process and did surfing through Google and found below points,

One - Load and Compile Header: In C++ every single unit of compilation needs, may be hundreds of headers to be Loaded and Compiled each time. Everyone of them typically has to be re-compiled for every single compilation unit. This is because, compiler thinks the result of compiling header may vary for every other unit, such like, a macro defined in one of the compilation unit may cause change in contents of header included for another compilation unit. So, the process has to be re-carried out for each and every single unit. This, probably could be main reason for C++ compiler to consume more time on compilation.
On the other hand, languages like Java or C# if you compare, they don't have to include headers, they can depend on binaries from the compilation of the used classes. This means, if object X is used in abc.java file, to get it compiled, it is enough for compiler to check binaries of X.class, it doesn't require to go deeper check looking for dependencies of X.class.

Two - Templates: In C# like languages, List<T> is the only type that is compiled, irrespective of type 'T' and irrespective of how many instantiation of List you have in program. On the other hand, C++ compiler behaves differently. For C++, vector<int> and vector<float> are entirely different entities to handle and each one needs to be re-compiled on each time.
Add to this, templates makes a full Turing-Complete "sub-language" that the compiler has to interpret with, and this can become ridiculously complicated. Even relatively simple template meta programming code can define recursive templates that create dozens and dozens of templates of instantiations. However, it is likely that templates may result in extremely complex types, with ridiculously long names, adding a lot of extra work to the linker. (It has to compare a lot of symbol names, and if these names can grow into many thousand characters, that can become fairly expensive).

Three - Linking: Once all units are compiled, all the object files need to be linked together. This is the process of monolithic linking and cannot be parallelized. So compiler has to process whole project.

Four - Optimization: C++ really allows very peculiar way of optimization. This whole optimazation process is a compiler dependent and may vary with different techniques. If you compare other programming languages like C# or Java, they don't allow complete optimization to happen on program, they don't allow complete elimination of class to happen, because of their feature 'reflection' [Reflection is used to describe a code which is able to inspect another piece of code]. But, even a simple C++ template metaprogram can easily generate dozens or hundreds of classes, all of which are inlined and eliminated again in the optimization phase. And again, for C++, it doesn't get second chance and compiler has to do optimization on compilation time only, compared with C# program which can rely on the JIT compiler to perform additional optimizations at load-time.

Five - Parsing: The C++ syntax is extremely complicated to parse, as it depends heavily on context, and is very hard to disambiguate. This takes a lot of time in compilation.

However, most of the above factors are shared by C program also, which compiles fairly and efficiently. Only offender I can see is 'Templates' in C++. Templates are useful, and make C++ a far more powerful language, but they also take their toll in terms of compilation speed.

Monday, 10 December 2012

Initialization Lists in C++

We all know, what happens when a class object is created; its Constructor is called. And, ofcorse that's not the end, it's base class constructor is also called. By default, the constructors invoked are the default ("no-argument") constructors. Moreover, all of these constructors are called before the class's own constructor is called.

So, with below piece of code,
class A 

public: 
     A()
     { 
          std::cout << "A's constructor" << std::endl; 
     } 
}; 

class B: public A
public: 
     B()
     { 
          std::cout << "B's constructor" << std::endl; 
     }
}; 

int main() 
{
     B obj1;
     return 0;
}
The object "obj1" is constructed in two stages: first, the A's constructor is invoked and then the B's constructor is invoked. The output of the above program will be to indicate that A's constructor is called first, followed by B's constructor. We all know this.

Why do this? There are a few reasons. First, each class should need to initialize things that belong to it, not things that belong to other classes. So a child class should hand off the work of constructing the portion of it that belongs to the parent class. Second, the child class may depend on these fields when initializing its own fields; therefore, the constructor needs to be called before the child class's constructor runs. In addition, all of the objects that belong to the class should be initialized so that the constructor can use them if it needs to.

Initialization List:
But what if you have a parent class that needs to take arguments to its constructor?
This is where initialization lists come into play. An initialization list immediately follows the constructor's signature, separated by a colon(:). Initialization List is another or a better approach for initializing the member variables (and base class objects) of a class upon construction of an instance of it's own.

Let's modify above code to demonstrate initialization list,

class A 

public: 
     A(int x)
     { 
          std::cout << "A's constructor is called with x = "<< x << std::endl;
     } 
}; 

class B: public A
public: 
     B() : A(100) //initialization list - construct A part of B
     { 
          std::cout << "B's constructor" << std::endl; 
     }
}; 

This is how you can construct and initialize base part of the child construct.

You can set-up order of constructors need to be called, before child constructor, separated by comma.
Like this,
class B: public A, public C
public: 
     B() : A(100), C(200)
     { 
          std::cout << "B's constructor" << std::endl; 
     }
}; 

The above call will be in sequential, as before B constructor, A part of B is initialized and then C part of B is initialized and after that only B's constructor is executed.

Here are interesting factors about initialization list:

> Initialization List is used to initialize both user defined data types (like embedded object of a class) and also primitive/built-in data types (like int, char).
Yes basically it is possible, look at below example,

class A 

public: 
     A(int x)
     { 
          std::cout << "A's constructor is called with x = "<< x << std::endl;
     } 
}; 

class B: public A
{
private:
     int x;
     int y;
public: 
     B() : A(100), x(25), y(50)
     { 
          std::cout << "B's constructor" << std::endl; 
     }
}; 

Above code initializes A part of B, then initializes two member variables 'x' and 'y' with constant values, before calling B's own constructor.

> Initialization List can appear irrespective of the place the constructor is defined.

> Initializing the member variables in the Initialization List is better than initializing them inside the body of the constructor of the class.

> Data members are initialized in the order they are declared, regardless of the order of their initialization.

> It is mandatory to initialize Reference Data Member in an Initialization List because it can not exist without being initialized.

> It is mandatory to initialize Constant Data Member in an Initialization List otherwise it would be constrructed with some junk values and we cannot initialize it later anywhere else.

> It is mandatory to construct and initialize, embedded class objects/base class objects in case of inheritance, in an Initialization List, if they do not themselves have a zero-argument/default constructor provided.

Great isn't it !!!!

Tuesday, 4 December 2012

Virtual Inheritance and Diamond Problem in C++

Multiple inheritance in C++ is a powerful, but tricky tool, that often leads to problems if not used carefully. One of the major problem that arises due to multiple inheritance is the diamond problem.

The "diamond problem" (sometimes referred to as the "deadly diamond of death") is an ambiguity that arises when two classes B and C inherit from A, and class D inherits from both B and C. If D calls a method defined in A (and does not override the method), and B and C have overridden that method differently, then from which class does it inherit: B, or C?

                         Class A
                       ____|____
                      /                 \  
               Class B         Class C 
                      \________ /    
                               |
                         Class D

Classic Example:

class Animal {
 public:
  virtual void eat();
};
 
class Mammal : public Animal {
 public:
  virtual void breathe();
};
 
class WingedAnimal : public Animal {
 public:
  virtual void flap();
};
 
// A bat is a winged mammal
class Bat : public Mammal, public WingedAnimal {
};
 
Bat bat;

As declared above, a call to bat.eat() is ambiguous because there are two Animal (indirect) base classes in Bat, so any Bat object has two different Animal base class sub-objects. So an attempt to directly bind a reference to the Animal sub-object of a Bat object would fail, since the binding is inherently ambiguous:

Bat b;
Animal &a = b; // error: which Animal subobject should a Bat cast into, 
               // a Mammal::Animal or a WingedAnimal::Animal?

Solution is in Virtual Inheritance:

And our re-implemented class looks like this,

class Animal {
 public:
  virtual void eat();
};
 
// Two classes virtually inheriting Animal:
class Mammal : public virtual Animal {
 public:
  virtual void breathe();
};
 
class WingedAnimal : public virtual Animal {
 public:
  virtual void flap();
};
 
// A bat is still a winged mammal
class Bat : public Mammal, public WingedAnimal {
};


The Animal portion of Bat::WingedAnimal is now the same Animal instance as the one used by Bat::Mammal, which is to say that a Bat has only one, shared, Animal instance in its representation and so a call to Bat::eat() is unambiguous. Additionally, a direct cast from Bat to Animal is also unambiguous, now that there exists only one Animal instance which Bat could be converted to.

This is implemented by providing Mammal and WingedAnimal with a vtable pointer (or "vpointer") since the memory offset between the beginning of a Mammal and of its Animal part is unknown until runtime. Thus Bat becomes (vpointer, Mammal, vpointer, WingedAnimal, Bat, Animal). There are two vtable pointers, one per inheritance hierarchy that virtually inherits Animal. In this example, one for Mammal and one for WingedAnimal. The object size has therefore increased by two pointers, but now there is only one Animal and no ambiguity. All objects of type Bat will have the same vpointers, but each Bat object will contain its own unique Animal object. If another class inherits from Mammal, such as Squirrel, then the vpointer in the Mammal object in a Squirrelwill be different from the vpointer in the Mammal object in a Bat, although they can still be essentially the same in the special case that the Squirrel part of the object has the same size as the Batpart, because then the distance from the Mammal to the Animal part is the same. The vtables are not really the same, but all essential information in them (the distance) is.

Reference variable in c++

C++ references allow you to create a second name for the a variable that you can use to read or modify the original data stored in that variable. While this may not sound appealing at first, what this means is that when you declare a reference and assign it a variable, it will allow you to treat the reference exactly as though it were the original variable for the purpose of accessing and modifying the value of the original variable--even if the second name (the reference) is located within a different scope. This means, for instance, that if you make your function arguments references, and you will effectively have a way to change the original data passed into the function. This is quite different from how C++ normally works, where you have arguments to a function copied into new variables. It also allows you to dramatically reduce the amount of copying that takes place behind the scenes, both with functions and in other areas of C++, like catch clauses.

Declaration is,
int& ref = <some_int_variable>;

For Example,
int x; 
int& foo = x; // foo is now a reference to x so this sets x to 56 
foo = 56; 
std::cout << x <<std::endl;

What are the difference between Reference Variable and conventional pointers?

> A pointer can be re-assigned any number of times while a reference can not be reassigned after initialization.
> A pointer can point to NULL while reference can never point to NULL
> You can't take the address of a reference like you can with pointers
> There's no "reference arithmetic" (but you can take the address of an object pointed by a reference and do pointer arithmetic on it as in &obj + 5).

End Line: Beware of references to dynamically allocated memory. One problem is that when you use references, it's not clear that the memory backing the reference needs to be deallocated--it usually doesn't, after all. This can be fine when you're passing data into a function since the function would generally not be responsible for de-allocating the memory anyway. 

On the other hand, if you return a reference to dynamically allocated memory, then you're asking for trouble since it won't be clear that there is something that needs to be cleaned up by the function caller.