Showing posts with label Programming. Show all posts
Showing posts with label Programming. Show all posts

Sunday, June 28, 2020

C++ concepts

Vector




Vectors are sequence containers representing arrays that can change in size. Vectors in C++ are preferable when managing ever-changing data elements.

Example: 
vector PersonalId (1000);

Just like arrays, vectors use contiguous storage locations for their elements, which means that their elements can also be accessed using offsets on regular pointers to its elements, and just as efficiently as in arrays. But unlike arrays, their size can change dynamically, with their storage being handled automatically by the container.

Internally, vectors use a dynamically allocated array to store their elements. This array may need to be reallocated in order to grow in size when new elements are inserted, which implies allocating a new array and moving all elements to it. This is a relatively expensive task in terms of processing time, and thus, vectors do not reallocate each time an element is added to the container.

Instead, vector containers may allocate some extra storage to accommodate for possible growth, and thus the container may have an actual capacity greater than the storage strictly needed to contain its elements (i.e., its size). Libraries can implement different strategies for growth to balance between memory usage and reallocations, but in any case, reallocations should only happen at logarithmically growing intervals of size so that the insertion of individual elements at the end of the vector can be provided with amortized constant time complexity (see push_back).

Therefore, compared to arrays, vectors consume more memory in exchange for the ability to manage storage and grow dynamically in an efficient way.

Compared to the other dynamic sequence containers (dequeslists and forward_lists), vectors are very efficient accessing its elements (just like arrays) and relatively efficient adding or removing elements from its end. For operations that involve inserting or removing elements at positions other than the end, they perform worse than the others, and have less consistent iterators and references than lists and forward_lists.


Virtual

A virtual function is a member function in the base class that you expect to redefine in derived classes.

The goal of object-oriented programming is to divide a complex problem into small sets. This helps understand and work with problem in an efficient way. Sometimes, it's desirable to use inheritance just for the case of better visualization of the problem. In C++, you can create an abstract class that cannot be instantiated (you cannot create object of that class). However, you can derive a class from it and instantiate object of the derived class. Abstract classes are the base class which cannot be instantiated.

A virtual function whose declaration ends with =0 is called a pure virtual function.
Any C++ class with at least one pure virtual function is considered to be an abstract class.

Function Template

Function templates are functions that serve as a pattern for creating other similar functions. The basic idea behind function templates is to create a function without having to specify the exact type(s) of some or all of the variables. Instead, we define the function using placeholder types, called template type parameters. Once we have created a function using these placeholder types, we have effectively created a “function stencil”.

When you call a template function, the compiler “stencils” out a copy of the template, replacing the placeholder types with the actual variable types from the parameters in your function call! Using this methodology, the compiler can create multiple “flavors” of a function from one template! 

Example:

template
T add(T num1, T num2)
{
   return (num1 + num2);
}

int main() {

    int result1;
    double result2;
    // calling with int parameters
    result1 = add(2, 3);
    cout << result1 << endl;

    // calling with double parameters
    result2 = add(2.2, 3.3);
    cout << result2 << endl;

    return 0;
}    





Thursday, October 15, 2009

Differences between Java and C++ in terms of OOP

Most  people start learning Object Oriented Programming from either Java and/or C++.  Although the concept of Object Oriented Programming is the same (in fact, you can even do Object oriented programming without use any OO language), there are subtle difference between Java and C++ from OOP perspective.  I try to list some of the key differences for reference, you are welcome to comment. Please note the grammar differences are not the interest point of this blog.

All stand-alone C++ programs require a function named main and can have numerous other functions. Java does not have stand alone functions, all functions (called methods) are members of a class. All classes in Java ultimately inherit from the Object class, while it is possible to create inheritance trees that are completely unrelated to one another in C++.  In summary, Java is a pure Object oriented language, while C++ is a mixture of Object oriented and structure language.

The interface keyword in Java is used to create the equivalence of an abstract base class containing only method declarations and constants. No variable data members or method definitions are allowed. C++ does not support interface concept. Java does not support multiple inheritance. To some extent, the interface feature provides the desirable features of multiple inheritance to a Java program without some of the underlying problems.

Java is running on a Virtual Machine, which can recollect unused memory to the operating system, so Java does not destructor.  Unlike C++, Java cannot access pointers to do memory operation directly. This leads to a whole host of subtle and extremely important differences between Java and C++. 

Furthermore, the C++ compiler does not check whether all local variables are initialized before they are read. It is quite easy to forget initializing a variable in C++. The value of the variable is then the random bit pattern that happened to be in the memory location that the local variable occupies.

Java does not have global functions and global data. Static in Java is just like global in C++, can be accessed through class name directly, and shared by all instances of the class.  For C++, static data members must be defined out side of class definition, because they don't belong to any specific instance of the class.

Generally Java is more robust than C++ because:

  • Object handles (references) are automatically initialized to null.
  • Handles are checked before accessing, and exceptions are thrown in the event of problems.
  • You cannot access an array out of bounds.
  • Memory leaks are prevented by automatic garbage collection.

While C++ programmer clearly has more flexibility to create high efficient program, also more chance to encounter error.

Monday, October 12, 2009

Difference between Stack memory and Heap Memory.

Recently I came across the difference between stack/heap topic. In simple, Both are dynamic memory allocated for program execution, but not the only 2 memory regions allocated for program execution.

Please Google “stack, heap” for the definition, summary for the difference:

Heap
- free-list - list of free space
- on allocation - memory manager finds space and marks it as used changing free-list
- on de-allocation - memory manager marks space as free changing free-list
- memory fragmentation - memory fragments into small blocks over lifetime of program
- garbage collection - coalesce fragments, possibly moving objects (must be careful of pointers when moving!)
- Concept at Operating system Memory management layer.

Stack
- clean and efficient support for nested functions and recursion
- central concept is stack frame (also called activation record)
- Concept at Micro Processor hardware registers layer.

Simple Example:

void foo()
{
    int x;                     <<< x is on the stack
    char *ptr = new char[255];
<<< 255 characters are allocated in the heap, but ptr object is on the stack
    int array[255];            <<< 255 ints are all on the stack
}

Saturday, October 10, 2009

Programming

Most people think that programming is only writing several lines of code. Actually a good programmer needs not only to understand programming language syntax very well, but also to play around with many tools and build up good programming practice. There ARE some super star programmers, but super star programmers could spoil your delivery since only he knows everything. When it comes to the customer support stage, he will be too busy to answer all the questions. One day he left the company, Wow, nobody can take over his job. The good software must be the collaboration result of the development team, test team and many support teams, plus your customer.

I tried to express my software engineering experience from technical perspective, there is an article on software engineering from project organization perspective in this website also.

First of all, some software processing people believe that the “bug density” of software is from software processing and quality control only, it should be independent of people. Yes, it IS from process and quality. However, the project organization, tech leader’s technical capability and whether the team are willing to do the project (don’t laugh, it is true sometime people just get annoyed and don’t want to do anything).

1. GNU development tools on Linux. 1

2. Other Tools. 1

3. Programming Languages. 1

4. Good practices. 2

1. GNU development tools on Linux

GNU development tools are a complete set of framework. They are absolutely free and powerful. Some people say that there is nothing but the GNU way to develop software, a typical Linux/UNIX software developer uses in his everyday work. GNU development tools are not worse than any other commercial (expensive) so called "killer-apps" widely used on other platforms. GNU tools are your friends for any development work done on Linux. Before you want to purchase new software development tools, think it over, I bet you could have a GNU solution to satisfy your requirement.

GNU native tools

This set of tools are used for x86/Linux native development I used to play with.

GNU cross tools

Linux platform virtually supports everything required for embedded development. Some company had to use windows cross-development environment simply because historical reasons. You may find information on Linux cross development environment here.

2. Other Tools

Other tools

However, there are still some commercial tools you should know. Anyway, everyone want to use free tools and sell their product with high price. If nobody buy commercial tools, many software engineer will lost their job also.

3. Programming Languages

Programming Languages

4. Good practices

Good Practice

The best practice for programming

I was asked about the best practice of programming.  As far as I know.  There are plenty of such documents available online. So I just list something I learned from my passed projects. Most of them are independent of any programming language, some even not direct related to coding. But I like the saying: There is more to driving than knowing how to operate a car.

1. Communication! Communication! Communication! Talk to anyone you think necessary within the development team, from expert to novice. Present the idea in diagram. Make sure all developers are working with each other, not against each other. I myself feel boring to read theory more than half day, the learning/training must be through the iteration of hands-on/discussion/thinking/reading. This is not limited to programming.  The thumb-rule is all developers must know they are coding towards the right common goal, which is more important than any so called best practice. Obviously if your organization set wrong direction, then we cannot help at this level.

2. Always define meaningful naming convention for everything, like variable, function, conditional flags. Try to make the code self-explained. I am not saying we can ignore comment, but it is hard (if not next-to-impossible) to ensure everyone always keep their comment sync with code in a large project.

3. Always define a coding style (even you are the only developer). Enforce coding style by static checking tools if necessary. There are auto-formatting tools, but I think those are useless for big project.

4. Pay attention to the default case. Assume there are 2 possibilities: A, and B. Be careful to use

   if A   do something for A;

   else   do something for B.

One day if you have possibilities: C, the above example will be a bug, and so on for switch, ..#if #else, ...  Try to make explicit condition, and create warning/generate some notice for error case;

5. Use debug macro and make sure the debug macro can be disabled per severity level or functional area, can be turned off (instead of remove) in the release code.

6. For a large project, make it clear for public or private functions, and have someway to detect error (compiler, script checker, etc) automatically.

7. A common error: if (  A=B ) instead of if( A==B ), which will assign the value of B to A, and execute the block with the new value of A, which is B. So be careful to have proper coding style, and you can check this by “grep” or script.

8. I like the Model based design, layered structure, and power-points to explain the flow in diagram, try to use these for documentation. BTW: If your model can be used to generate code, then it is a live modeling. Otherwise the development team will use it for a while for various reasons, but later the model will be dead.

9. For senior level developers/tech leaders, make sure you have a clear idea on logical partition, and software configuration management, or at least have an idea for discussion with management and developers. Make sure, more developers should mean more contribution to the final dead-line, NOT more chaos.