Pages

Tuesday, June 10, 2014

How to update the drive firmware in Linux



echo "Using firmware file $fwfile for upgrading $product on device $x…"

The process to download in Solid State Drive and Hard Disk Drive is a little different. In case of SDD we can burn the firmware in one command, but in case of HDD we need to write in a loop since there is a limitation of 0x80000 bytes on VFS module system call.



           if [ "$rev" != "$target_fw_ver" ]; then
               echo "Upgrading $disk_type firmware to version $target_fw_ver on $x i.e.$sg_dev..."
               if  [ "$disk_type" = "ssd" ]; then
                   sg_write_buffer --in=${fwfile} --mode=5 --id=0 $sg_dev
                   if [ $? -ne 0 ]; then
                       echo "Failed to upgrade SSD firmware on $x i.e.$sg_dev to version $target_fw_ver!" >&2
                       exit 1
                   fi
               else
                   # hdd firmware upgrade
                   bytes=`ls -l $fwfile | awk '{ print $5; }'`
                   start=0
       #length = 0x80000 Bytes
                   length=524288
                   while [ $start -lt $bytes ]; do
                       if let 'start+length>bytes'; then
                           let 'length=bytes-start'
                       fi
                       sg_write_buffer --in=$fwfile --skip=$start --offset=$start --length=$length --mode=0x7 --id=0 $sg_dev
                       if [ $? -ne 0 ]; then
                           echo "Failed to upgrade HDD firmware $x i.e.$sg_dev to version $target_fw_ver!" >&2
                           exit 1
                       fi
                       let start+=length
                   done
               fi

Wednesday, October 31, 2012

Let's see what you installed

Google+
To install packages in Linux:
Packages can be installed using yum, or rpm. Each one has it's own internal database that list what is already installed into the system.

To install a package using yum:
#yum install

To install a package using rpm:
#rpm -ivh
#rpm -Uvh

To check what is already installed:

To check what is yum installed:
#yum list | grep


To check what is rpm installed:
#rpm -qa | grep



HTH
--kongkon

Tuesday, October 23, 2012

How to grep in shell script...

The task is there is a file containing one column of entries. Write a script to compare the o/p of one command and check whether the output matches with any row of that file (supported.txt file).

$cat supported.txt
SAS2308_2(C1)
SAS2308_2(D1)

Assume $devInfo gives us a string that contains like the rows of support.txt file. If there is a match between the o/p of $devInfo in that file, then do nothing, else warn.

checkSupportedFwDev() {
        local supportedControllerList=`cat supported.txt`
        #Get the controller name from $devInfo and compare that with $supportedControllerList
        local currentController=`echo "${devInfo}" | grep "Controller" |grep -v Number | awk '{ print $NF }'`
        #echo "currentController=[$currentController]"
        local supported=`echo "${supportedControllerList}" | grep $currentController`
        if [ -z ${supported} ]
        then
                echo "Warning: This adapter [${currentController}] is not officially supported."
        fi
        }

Another approach to do the same:

checkSupportedFwDev() { 
        #Get the controller name from $devInfo and compare that with $supportedControllerList
        local currentController=`echo "${devInfo}" | grep "Controller" |grep -v Number | awk '{ print $NF }'`

        if ! grep "^${currentController}\$" supported.txt >/dev/null 2>&1;
        then
                echo "Warning: This adapter [${currentController}] is not officially supported."
        fi

}

Which approach you like and why?





Friday, October 12, 2012

Vi tricks

How to set the line numbers into vi editor?
Everyone knows this:
a) cd
-- go to home directory
b) edit(create if not there) a file called .exrc, and all this line
set nu
or set number
Simple.

But, what I al now looking at is how to set the vi line numbering in only a special work directory, say /home/kdutta/mywork. I do not want to set vi line numbering to all directories, at times this is annoying.
Putting a .exrc file into /home/kdutta/mywork/.exrc does not seem to work, here, even if I source it.

Do you know, how to do that?

Thursday, September 27, 2012

Difference between $variable and ${variable} in (bash) shell scripting

Many often we do shell scripting, but small small ignorance at times cost a lot. Here is an example of what we mean and what it become.
[/tmp]$ cat try.sh #! /bin/sh a=12 b=34 echo $a_$b echo ${a}_$b [vivarkey@/tmp]$ sh try.sh 34 12_34 [/tmp]$


In the above shell script we intended to print "variableA_variableB", in the shell script on last but one line. But since we missed the braces around the variable it actually truncated the previous variable along with the '-' symbol.

NB: This code snippet is tried in bash shell on Linux, on mac it gives different result.

HTH
Kongkon

Playing with RPM

Ever wondered after running the rpm --install (or rpm -ivh) command what happened, what sort of files created in the file system.

To find out the list of files that an already installed rpm spawned:
rpm -ql
NB: there is no .rpm after the package name here in this command.

[root@localhost release]# rpm -qa|grep lsifw-tools-xrtx
lsifw-tools-xrtx-1-1.xrtx.1872.noarch
[root@localhost release]# rpm -ql lsifw-tools-xrtx-1-1.xrtx.1872.noarch
/lib/firmware/lsi/.NOT_RELEASE_DIR
/lib/firmware/lsi/FirmwareID.sh
/lib/firmware/lsi/xrtx_lsifw.sh
/usr/share/man/man8/xrtx_lsifw.8.gz
[root@localhost release]# 



To find out the list of files that an rpm will generate once you install the rpm:
rpm -qlp

[root@localhost tmp]# rpm -qlp /tmp/lsifw-tools-xrtx-1-1.xrtx.1872.src.rpm
lsifw-tools-xrtx-source.spec
lsifw-tools-xrtx.tgz
[root@localhost tmp]#


HTH
Kongkon

Monday, June 18, 2012

C++ Library Problem

Google+

C++ Library Problem

You have a library provided by the vendor. All you have is header files and library files. Library contains the class "Shape" and there is whole hierarchy tree (I mean classes which derive from this base class).

Now you want to add some function "getArea" (not originally present in the class or any of its derived class) in the class "Shape" , you don't have the source code.
Using this library, you have written a lot of code. Now, you have to make some changes so that, any object of "Shape" class (or its derived class) will be able to call this function.

With your strategy, you should be able to override the definition of this function in the derived class.

http://www.careercup.com/question?id=13872673


Wednesday, December 14, 2011

A simple C program

Let's talk about simplicity. And let's look at a simple C program today. Why not, every day we deal with complex problem, so let's talk about a simple C program now. Here is the program;

main()

{

    char *p1="name";

    char *p2;

    p2=(char*)malloc(20);

    memset (p2, 0, 20);

    while(*p2++ = *p1++);

    printf("%s\n", p2);

}

Well, what does this program do. This is the topic of today's blog.

Ans:

Looks like this program output's the string name , but that's not true.

What do you think about this program?

Write your comments about it.

Thursday, November 24, 2011

All about C++ templates





Templates in C++ can be of class template or function template.
A template is used as a mechanism to generalize the parameter type we pass to either the class or function. This extends the function overloading concept of C++. Template takes the C++ concept of polymorphism to the next level.


Here is a example of function templates:
Let's say we have a swap function that swaps two variables of type T.

void f(int a, int b, float m, float n)
{
    swap(a, b);      //swap two integer values
    swap(m, n);      //swaps two float values
}

We can write a template function to do this as below:

template <class T>
void swap (T &x, T &y)
{
    T temp = x;
    x = y;
    y = T;
}

Similarly we have class template where we can pass any type of parameter using the template T.

template < class T>
class vector
{
     T *v; //type T vector, T can be int, float, anything
     int size;
   public:
     vector (int m)
     {
     v = new T[size = m]; // v is an array of type T
     //initialize the array
       for (int i = 0; i < size; i++)
         v[i] = 0;
    }

}


This is an example of a class vector which initialize an object of type T of array. Invoke it this way:
     vector < int> v1(10);    //a vector class of int
     vector < float> v2(20);    //a vector class of float



Q1. Find the o/p of the code snippet:
template < class T, int l=7> class Foo {
     static const T k = l;
     int q;

   public:
     Foo(int x = l) : q(x)
     { }
     T GetQ() const { return q; }
}

void f() {
     Foo < long, 9> foo(10);
     std :: cout << foo.GetQ();

}

Ans:
Explaination:
Default values for template parameters

Template parameters may have default values, and when instantiating the template these values can be omitted. Here’s an example:

template <typename T=int, int N=10>
class Foo {
};

Foo<float, 42> foo1;
Foo<double> foo2;
Foo<> foo3;

Note specifically the strange syntax for the definition of foo3, which means that it instantiates the Foo template with all parameters assigned their default values. Default values may only be specified for class templates.

Q2. What is STL?
Ans: STL is the C++ Standard Template Library. Instead of writing your own, you can use templates from STL just like other library functions that we use from any other C/C++ library. It is a collections of class templates and function templates. We sahould use template library as it is bug free rather than writing our own like inventing the wheel again.


In tehnical terms:
The Standard Template Libraries (STL's) are a set of C++ template classes to provide common programming data structures and functions such as doubly linked lists (list), paired arrays (map), expandable arrays (vector), large string storage and manipulation (rope), etc. The STL library is available from the STL home page. This is also your best detailed reference for all of the STL class functions available. STL can be categorized into the following groupings:

Here is the greatest post about C++ Templates:
http://eli.thegreenplace.net/2011/04/22/c-template-syntax-patterns/

Q3. What is partial specialization or template specialization?

Q4. How can you force instantiation of a template?

Q5. What is an iterator?

Q6. What is an algorithm (in terms of the STL/C++ standard library)?

Saturday, October 22, 2011




Hello World!

How about compiling a C programming right from the browser itself.
Here it is:

Best C/C++/Data Structure Programming books




C/C++ Programming Questions This blog is for C/C++ Programming
Here is my collection of some of the best Programming books.

No 1 has to be this:






Then comes the rest of them.
When it comes to data structure there is a book written in simple English, very easy to comprehend the basic fundamentals of computer science.


There are couple of C++ books. But I find this to be the best:


        C++
        How to Program by Deitel and Deitel


And here a list of best Linux programming books:
a) Linux Kernel



b) Linux Device Driver Programming


Enjoy, happy reading.

Regards,
Kongkon


Friday, October 21, 2011

Free Linux Machine with C compiler




Hello World!
Many of us wanted their own Linux machine to do some C programming or at least to get a feel of the Linux Operating System.

Here is a Linux machine which can be accessible over the internet free of cost only for you :-). 

Just type the following URL in the browser and here you are in your own Linux machine:


http://bellard.org/jslinux/


This is an amaizing work by Bellard. There is also a clipboard facility to copy/paste your work back and forth between your local system and the Linux machine.

Copy your file to the clipboard:
cat myfile > /dev/clipboard

Explore this machine, and I am sure you will have lots of fun. The best part is that there is a C Compiler to test your own C programs.
It's a tiny version of a C compiler called "tcc".


To have a deep dive into the booting process of this OS, look at the booting sequence:

Linux version 2.6.20 (bellard@voyager) (gcc version 3.4.6 20060404 (Red Hat 3.4.6-9)) #2 Mon Aug 8 23:51:02 CEST 2011
BIOS-provided physical RAM map:
sanitize start
sanitize bail 0
 BIOS-e801: 0000000000000000 - 000000000009f000 (usable)
 BIOS-e801: 0000000000100000 - 0000000001000000 (usable)
16MB LOWMEM available.
Entering add_active_range(0, 0, 4096) 0 entries of 256 used
Zone PFN ranges:
  DMA             0 ->     4096
  Normal       4096 ->     4096
early_node_map[1] active PFN ranges
    0:        0 ->     4096
On node 0 totalpages: 4096
  DMA zone: 32 pages used for memmap
  DMA zone: 0 pages reserved
  DMA zone: 4064 pages, LIFO batch:0
  Normal zone: 0 pages used for memmap
DMI not present or invalid.
Allocating PCI resources starting at 10000000 (gap: 01000000:ff000000)
Detected 3.333 MHz processor.
Built 1 zonelists.  Total pages: 4064
Kernel command line: console=ttyS0 root=/dev/ram0 rw init=/sbin/init notsc=1
Initializing CPU#0
Disabling TSC...
PID hash table entries: 64 (order: 6, 256 bytes)
Console: colour dummy device 80x25
Dentry cache hash table entries: 2048 (order: 1, 8192 bytes)
Inode-cache hash table entries: 1024 (order: 0, 4096 bytes)
Memory: 11956k/16384k available (1265k kernel code, 4040k reserved, 324k data, 124k init, 0k highmem)
virtual kernel memory layout:
    fixmap  : 0xffffc000 - 0xfffff000   (  12 kB)
    vmalloc : 0xc1800000 - 0xffffa000   ( 999 MB)
    lowmem  : 0xc0000000 - 0xc1000000   (  16 MB)
      .init : 0xc0290000 - 0xc02af000   ( 124 kB)
      .data : 0xc023c503 - 0xc028d854   ( 324 kB)
      .text : 0xc0100000 - 0xc023c503   (1265 kB)
Checking if this processor honours the WP bit even in supervisor mode... Ok.
Calibrating delay using timer specific routine.. 20.22 BogoMIPS (lpj=101116)
Mount-cache hash table entries: 512
CPU: After generic identify, caps: 00000010 00000000 00000000 00000000 00000000 00000000 00000000
Intel Pentium with F0 0F bug - workaround enabled.

CPU: After all inits, caps: 00000000 00000000 00000000 00000000 00000000 00000000 00000000
Compat vDSO mapped to ffffe000.
CPU: Intel Pentium MMX stepping 03
Checking 'hlt' instruction... OK.
NET: Registered protocol family 16
Setting up standard PCI resources
NET: Registered protocol family 2
IP route cache hash table entries: 1024 (order: 0, 4096 bytes)
TCP established hash table entries: 1024 (order: 0, 4096 bytes)
TCP bind hash table entries: 512 (order: -1, 2048 bytes)
TCP: Hash tables configured (established 1024 bind 512)
TCP reno registered
checking if image is initramfs...it isn't (bad gzip magic numbers); looks like an initrd
Freeing initrd memory: 2048k freed
Total HugeTLB memory allocated, 0
io scheduler noop registered
io scheduler anticipatory registered
io scheduler deadline registered
io scheduler cfq registered (default)
Real Time Clock Driver v1.12ac
JS clipboard: I/O at 0x03c0
Serial: 8250/16550 driver $Revision: 1.90 $ 4 ports, IRQ sharing disabled
serial8250: ttyS0 at I/O 0x3f8 (irq = 4) is a 16450
RAMDISK driver initialized: 16 RAM disks of 4096K size 1024 blocksize
loop: loaded (max 8 devices)
TCP cubic registered
NET: Registered protocol family 1
NET: Registered protocol family 17
Using IPI Shortcut mode
Time: pit clocksource has been installed.
RAMDISK: ext2 filesystem found at block 0
RAMDISK: Loading 2048KiB [1 disk] into ram disk... | / - \ | / - \ | / - \ | / - \ | / - \ | / - \ | / - \ | / - \ | / - \ | / - \ | / - \ | / - \ | / - \ | / - \ | / - \ | / - \ | / - \ | / - \ | / - \ | / - \ | / - \ | / - \ | / - \ | / - \ | / - \ | / - \ | / - \ | / - \ | / - \ | / - \ | / - \ | / - \ done.
EXT2-fs warning: maximal mount count reached, running e2fsck is recommended
VFS: Mounted root (ext2 filesystem).
Freeing unused kernel memory: 124k freed
 


Enjoy this. We shall explore more later.







RIP Dennis Ritchie




Dennis Ritchie

 

The great Dennis Ritchie, the creator of C Programming Language, the reason behind which this programming blog exist today, died on 12th October 2011, at the age of 70.  

Here is a small C program as a tribute to Dennis Ritchie.

 

main() {

        printf("1941: Hello World!\n");

        printf("2011: RIP Dennis Ritchie\n");

}


Friday, May 20, 2011

Test your own C Programming skills





Hello World!

Good morning C programmers. Here is a compilation of couple of C and C++ questions to test your C/C++ programming knowledge. Most of the time you will be facing similar questions in job interviews for Software engineer or programmer not only at the fresher level but also at a very senior level. Many companies expect you to be hands on even at senior level. C is a programming language which is easy and at the same time extremely difficult if asked about complex pointer related questions. So, one has to be extremely careful in answering such questions.







Q1. Find the o/p:
main()
{
    char *ptr="hello";
    char ary[]="world";

printf("PTR: &ptr=%x, ptr=%x, *ptr=%x, ptr[0]=%x\n", &ptr,ptr, *ptr, ptr[0]);
printf("ARY: &ary=%x,ary=%x, *ary=%x, ary[0]=%x\n", &ary, ary, *ary, ary[0]);
}

Ans:


Q2. Find the o/p:
main()
{
    struct node {
        char a;
        int b; 
        short c;
        struct node next;
    }n1;   

printf("Ans1:%d\n", sizeof(n1));

return 0;
}

Ans:


Q3. Find the o/p:
main()
{
    struct node {
        char a;
        int b; 
        short c;
        struct node *next;
    }n1;   

printf("Ans1:\n\t node=%x\n \t node+2=%x\n", (char *)&n1, (char *)&n1+2);
printf("Ans2:%d\n", sizeof(n1));

return 0;
}
Ans:


Q4. What is the difference between fopen() and open()? When do you choose to use one over the other?

Ans:



Q5. Find the o/p:
main()
{
if(!printf("Hello ")){}
else
printf("World!");
}
Ans:


Q6. Find the o/p:
main()
{
struct i{
int a;    //4
double b;    //8
char * c;    //4
char d[7];    //8
short e;    //4
int f;    //4
};
printf("sizeof(i)= %d", sizeof(struct i));
}
Ans:


Q6.1. Find the o/p:
main()
{
struct i{
int a;    //4
double b;    //8
char * c;    //4
char d[3];    //4
short e;    //4
int f;    //4
};
printf("sizeof(i)= %d", sizeof(struct i));
}
Ans:



Q7. Find the o/p:
# include < stdio.h >
void main()
{
printf(NULL) ;
return ;
}
Ans:


Q8. Find the o/p:
# include < stdio.h >
void main()
{
int i = 0;
printf(i) ;
return ;
}
Ans:


Q9. Find the o/p:
#include <stdio.h>
void main()
{
printf("%s",NULL) ;
return ;
}
Ans:


Q10. Find the o/p of this last one:
main()
{
printf("%%",7);
}
Ans:


Q11. How do I declare an array of N pointers to functions returning pointers to functions returning pointers to characters?
Ans:


Q12. What is asmlinkage and what is it's use?
Ans:


Q13. What is output?
main()
{
printf("%x",-1<<4); }

Ans:

Link to the earlier post: Test your programming skills.

Enjoy yourself.
Regards,
Kongkon





Tuesday, March 08, 2011

Single Linked List using C




Here is a single linked list data structure using C Language:


#include

struct node {
        int data;
        struct node * next;
};

struct node *first = NULL;

int menu();

struct node * insert_node(int data);
struct node * delete_node(int data);
int count_node(struct node *);
int traverse_list(struct node *);


int menu()
{
int item = 0;

return item;
}

/*
* This routine will insert a new node to the left hand side of a linked list. And make this new node as the first node after insertion.
*/
struct node * insert_node(int data)
{
        struct node * temp = NULL;

        temp = (struct node *)malloc(sizeof(struct node));
        if (!temp)
                printf("Not enough memory in the system\n");

        // insert data;
        temp->data = data;

        if(first == NULL)
        {
                first = temp;
                temp->next = NULL;
                //printf("data=%d\n", temp->data);
        }
        else
        {
                temp->next = first;
                first = temp;
        }

return first;
}
/*
delete_node(int data) deletes the first node from the singly linked list where the data matches, and returns the starting of the list.
*/
struct node * delete_node(int data)
{
struct node * current = first, *prev;
//search the list for the first occurance of "data". If no node with "data" found then the list remains the same.

        while(current && current->data!=data)
        {
                prev = current;
                current=current->next;
        }
        prev->next = current->next;
        free(current);

return first;
}
int traverse_list(struct node *list_head)
{
        struct node * current, *prev;

        if (!first)
                printf("Empty list\n");

        current = first;
        prev = current->next;
        printf("\n\nList = ");
#if 1
        while(current)
        {
                printf("\t %d", current->data);
                current = current->next;
        }
#endif
        printf("\n\n");
}

main()
{
insert_node(30);
insert_node(40);
insert_node(50);
insert_node(60);
insert_node(70);
traverse_list(first);

delete_node(50);
traverse_list(first);
return 0;
}


Result of running this program:
kongkon@Linkat-Luidia:~/sea> ./a.out


List =   70      60      50      40      30



List =   70      60      40      30

Monday, June 07, 2010

C




Today we shall discuss about a simple C program.
I would like to explain the difference between array and &array address.
So, let's start by taking a live question. 
Q. Find the o/p:
main()
{
    char *ptr="hello";
    char ary[]="world";

printf("Ans:\n");
printf("PTR: &ptr=%x, ptr=%x, *ptr=%x, ptr[0]=%x\n", &ptr,ptr, *ptr, ptr[0]);
printf("ARY: &ary=%x,ary=%x, *ary=%x, ary[0]=%x\n", &ary, ary, *ary, ary[0]);
}

Ans:
PTR: &ptr=bfb86990, ptr=8048524, *ptr=68, ptr[0]=68
ARY: &ary=bfb8698a,ary=bfb8698a, *ary=77, ary[0]=77

When you look at the output of array and &array you will find that they both are same. Why? But, whereas in the case of a character pointer (not a character array), they seems to differ. Why again?

We all know that an array is like a constant pointer, and the address of the arrary is also indicated by the name of the array itself. Hence, when we mention arrary and when we mention &array they both mean the same and point to the same location. Memory allocation also happens in the same area as the starting address of the array.
But, but in case of a character pointer, prt and &ptr points to two distinct and different locations. &ptr is the place which is used by the compiler itself to store the actual data string that is pointed by ptr. &ptr points to a .rodata area inside the data segment, accessible and allocated by the compiler itself.

That is the only reason, why you get a segmentation fault while trying to modify the data pointed by the ptr character pointer.



Friday, May 14, 2010

C++ questions: Part 8




Q. Why the size of empty Class is one byte?
Ans:
Yes, the compiler will generate 1 byte of memory to mark the existence of the class.  This doesn't answer WHY though.  The reason is the language standard states that all classes must have a memory size of at least 1 byte so that the class doesn't occupy the same memory space with another class.  This is to prevent name mangling.  i.e., if I declare a class A {};, the compiler will still generate an entry in its table to something called "A".  If behind that I declare another class, say class B, if A takes 0 bytes of memory, and B's data gets written in the place where A was declared.  In this case, an instantiation of A would take on the properties of B. 

Q. What are the default methods of every object?
Ans:
http://qiang-ma.blogspot.com/2007/06/c-default-methods.html
 +---------------------------------------------------------+
|What Name |
+---------------------------------------------------------+
|Default Constructor A::A() |
|Copy Constructor A::A(const A &) |
|Assignment [const] A &A::operator=(const A &) |
|Destructor A::~A() |
+---------------------------------------------------------+


Q. Why a constructor can't be virtual?
Ans:

A constructor can not be virtual because at the time when the constructor is invoked the virtual table (vtable) would not be available in the memory.

Virtual allows us to call a function knowing only the interfaces and not the exact type of the object. To create an object you need complete information. In particular, you need to know the what you want to create exactly. Hence call to a constructor can't be virtual.

Friday, November 13, 2009

C++ questions: Part 7




C++ Q1: What are the steps involved in designing?
Answer: Before getting into the design the designer should go through the SRS prepared by the System Analyst.
The main tasks of design are Architectural Design and Detailed Design.
In Architectural Design we find what are the main modules in the problem domain.
In Detailed Design we find what should be done within each module.

C++ Q2: What are the main underlying concepts of object orientation?
Answer: Objects, messages, class, inheritance and polymorphism are the main concepts of object orientation.

C++ Q3: What do you meant by "SBI" of an object?
Answer: SBI stands for State, Behavior and Identity. Since every object has the above three.
Ø State:
It is just a value to the attribute of an object at a particular time.
Ø Behaviour:
It describes the actions and their reactions of that object.
Ø Identity:
An object has an identity that characterizes its own existence. The identity makes it possible to distinguish any object in an unambiguous way, and independently from its state.

C++ Q4: Differentiate persistent & non-persistent objects?
Answer: Persistent refers to an object's ability to transcend time or space. A persistent object stores/saves its state in a permanent storage system with out losing the information represented by the object.
A non-persistent object is said to be transient or ephemeral. By default objects are considered as non-persistent.

C++ Q5: What do you meant by active and passive objects?
Answer: Active objects are one which instigate an interaction which owns a thread and they are responsible for handling control to other objects. In simple words it can be referred as client.
Passive objects are one, which passively waits for the message to be processed. It waits for another object that requires its services. In simple words it can be referred as server.

C++ Q6: What is meant by software development method?
Answer: Software development method describes how to model and build software systems in a reliable and reproducible way. To put it simple, methods that are used to represent ones' thinking using graphical notations.

C++ questions: Part 6






C++ Q1: What is a smart pointer?
Answer: A smart pointer is an object that acts, looks and feels like a normal pointer but offers more functionality. In C++, smart pointers are implemented as template classes that encapsulate a pointer and override standard pointer operators. They have a number of advantages over regular pointers. They are guaranteed to be initialized as either null pointers or pointers to a heap object. Indirection through a null pointer is checked. No delete is ever necessary. Objects are automatically freed when the last pointer to them has gone away. One significant problem with these smart pointers is that unlike regular pointers, they don't respect inheritance. Smart pointers are unattractive for polymorphic code. Given below is an example for the implementation of smart pointers.

Example:
template
class smart_pointer
{
public:
smart_pointer(); // makes a null pointer
smart_pointer(const X& x) // makes pointer to copy of x
X& operator *( );
const X& operator*( ) const;
X* operator->() const;
smart_pointer(const smart_pointer &);
const smart_pointer & operator =(const smart_pointer&);
~smart_pointer():
private:
//...
};
This class implement a smart pointer to an object of type X. The object itself is located on the heap. Here is how to use it:
smart_pointer p= employee("Harris",1333);
Like other overloaded operators, p will behave like a regular pointer,
cout<<*p;


p->raise_salary(0.5);

C++ Q2: What is reflexive association?
Answer: The 'is-a' is called a reflexive association because the reflexive association permits classes to bear the is-a association not only with their super-classes but also with themselves. It differs from a 'specializes-from' as 'specializes-from' is usually used to describe the association between a super-class and a sub-class. For example:
Printer is-a printer.

C++ Q3: What is slicing?
Answer:Slicing means that the data added by a subclass are discarded when an object of the subclass is passed or returned by value or from a function expecting a base class object.
Explanation:
Consider the following class declaration:
class base
{
...
base& operator =(const base&);
base (const base&);
}
void fun( )
{
base e=m;
e=m;
}
As base copy functions don't know anything about the derived only the base part of the derived is copied. This is commonly referred to as slicing. One reason to pass objects of classes in a hierarchy is to avoid slicing. Other reasons are to preserve polymorphic behavior and to gain efficiency.

C++ Q4: What is name mangling?
Answer:Name mangling is the process through which your c++ compilers give each function in your program a unique name. In C++, all programs have at-least a few functions with the same name. Name mangling is a concession to the fact that linker always insists on all function names being unique.
Example:
In general, member names are made unique by concatenating the name of the member with that of the class e.g. given the declaration:
class Bar
{
public:
int ival;
...
};
ival becomes something like:
// a possible member name mangling
ival__3Bar
Consider this derivation:
class Foo : public Bar
{
public:
int ival;
...
}
The internal representation of a Foo object is the concatenation of its base and derived class members.
// Pseudo C++ code
// Internal representation of Foo
class Foo
{
public:
int ival__3Bar;
int ival__3Foo;
...
};
Unambiguous access of either ival members is achieved through name mangling. Member functions, because they can be overloaded, require an extensive mangling to provide each with a unique name. Here the compiler generates the same name for the two overloaded instances(Their argument lists make their instances unique).



C++ Q5: What are proxy objects?
Answer:Objects that points to other objects are called proxy objects or surrogates. Its an object that provides the same interface as its server object but does not have any functionality. During a method invocation, it routes data to the true server object and sends back the return value to the object.

C++ Q6: Differentiate between declaration and definition in C++.
Answer: A declaration introduces a name into the program; a definition provides a unique description of an entity (e.g. type, instance, and function). Declarations can be repeated in a given scope, it introduces a name in a given scope. There must be exactly one definition of every object, function or class used in a C++ program.
A declaration is a definition unless:
Ø it declares a function without specifying its body,
Ø it contains an extern specifier and no initializer or function body,
Ø it is the declaration of a static class data member without a class definition,
Ø it is a class name definition,
Ø it is a typedef declaration.
A definition is a declaration unless:
Ø it defines a static class data member,
Ø it defines a non-inline member function.

C++ Q7: What is cloning?
Answer: An object can carry out copying in two ways i.e. it can set itself to be a copy of another object, or it can return a copy of itself. The latter process is called cloning.

C++ Q8: Describe the main characteristics of static functions.
Answer: The main characteristics of static functions include,
Ø It is without the a this pointer,
Ø It can't directly access the non-static members of its class
Ø It can't be declared const, volatile or virtual.
Ø It doesn't need to be invoked through an object of its class, although for convenience, it may.

C++ Q9: Will the inline function be compiled as the inline function always? Justify.
Answer: An inline function is a request and not a command. Hence it won't be compiled as an inline function always.
Explanation:
Inline-expansion could fail if the inline function contains loops, the address of an inline function is used, or an inline function is called in a complex expression. The rules for inlining are compiler dependent.

C++ Q10: Define a way other than using the keyword inline to make a function inline.
Answer: The function must be defined inside the class.

C++ Q11: How can a '::' operator be used as unary operator?
Answer: The scope operator can be used to refer to members of the global namespace. Because the global namespace doesn’t have a name, the notation :: member-name refers to a member of the global namespace. This can be useful for referring to members of global namespace whose names have been hidden by names declared in nested local scope. Unless we specify to the compiler in which namespace to search for a declaration, the compiler simple searches the current scope, and any scopes in which the current scope is nested, to find the declaration for the name.

C++ Q12: What is placement new?
Answer: When you want to call a constructor directly, you use the placement new. Sometimes you have some raw memory that's already been allocated, and you need to construct an object in the memory you have. Operator new's special version placement new allows you to do it.

class Widget
{
public :
Widget(int widgetsize);
...
Widget* Construct_widget_int_buffer(void *buffer,int widgetsize)
{
return new(buffer) Widget(widgetsize);
}
};
This function returns a pointer to a Widget object that's constructed within the buffer passed to the function. Such a function might be useful for applications using shared memory or memory-mapped I/O, because objects in such applications must be placed at specific addresses or in memory allocated by special routines.

C++ Q13: What do you mean by analysis and design?
Answer:
Analysis:
Basically, it is the process of determining what needs to be done before how it should be done. In order to accomplish this, the developer refers the existing systems and documents. So, simply it is an art of discovery.
Design:
It is the process of adopting/choosing the one among the many, which best accomplishes the users needs. So, simply, it is compromising mechanism.