Saturday, June 14, 2014

How do function pointers in C work

Function Pointers and Callbacks in C 

A pointer is a special kind of variable that holds the address of another variable. The same concept applies to function pointers, except that instead of pointing to variables, they point to functions. If you declare an array, say, int a[10]; then the array name a will in most contexts (in an expression or passed as a function parameter) “decay” to a non-modifiable pointer to its first element (even though pointers and arrays are not equivalent while declaring/defining them, or when used as operands of the sizeof operator). In the same way, for int func();, func decays to a non-modifiable pointer to a function. You can think of func as a const pointer for the time being.
But can we declare a non-constant pointer to a function? Yes, we can — just like we declare a non-constant pointer to a variable:

int (*ptrFunc) ();
Here, ptrFunc is a pointer to a function that takes no arguments and returns an integer. DO NOT forget to put in the parenthesis, otherwise the compiler will assume that ptrFunc is a normal function name, which takes nothing and returns a pointer to an integer.
Let’s try some code. Check out the following simple program:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include
/* function prototype */
int func(int, int);
int main(void)
{
    int result;
    /* calling a function named func */
    result = func(10,20);       
    printf("result = %d\n",result);
    return 0;
}
/* func definition goes here */
int func(int x, int y)             
{
return x+y;
}
As expected, when we compile it with gcc -g -o example1 example1.c and invoke it with ./example1, the output is as follows:

result = 30
The above program calls func() the simple way. Let’s modify the program to call using a pointer to a function. Here’s the changed main() function:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include
int func(int, int);
int main(void)
{
    int result1,result2;
    /* declaring a pointer to a function which takes
       two int arguments and returns an integer as result */
    int (*ptrFunc)(int,int);
    /* assigning ptrFunc to func's address */                     
    ptrFunc=func;
    /* calling func() through explicit dereference */
    result1 = (*ptrFunc)(10,20);
    /* calling func() through implicit dereference */         
    result2 = ptrFunc(10,20);               
    printf("result1 = %d result2 = %d\n",result1,result2);
    return 0;
}
int func(int x, int y)
{
    return x+y;
}
The output has no surprises:

result1 = 30 result2 = 30

A Simple Call Back Function

At this stage, we have enough knowledge to deal with function callbacks. According to Wikipedia, “In computer programming, a callback is a reference to executable code, or a piece of executable code, that is passed as an argument to other code. This allows a lower-level software layer to call a subroutine (or function) defined in a higher-level layer.”
Let’s try one simple program to demonstrate this. The complete program has three files: callback.c, reg_callback.h and reg_callback.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/* callback.c */
#include
#include"reg_callback.h"
/* callback function definition goes here */
void my_callback(void)
{
    printf("inside my_callback\n");
}
int main(void)
{
    /* initialize function pointer to
    my_callback */
    callback ptr_my_callback=my_callback;                           
    printf("This is a program demonstrating function callback\n");
    /* register our callback function */
    register_callback(ptr_my_callback);                             
    printf("back inside main program\n");
    return 0;
}
1
2
3
/* reg_callback.h */
typedef void (*callback)(void);
void register_callback(callback ptr_reg_callback);
1
2
3
4
5
6
7
8
9
10
11
/* reg_callback.c */
#include
#include"reg_callback.h"
/* registration goes here */
void register_callback(callback ptr_reg_callback)
{
    printf("inside register_callback\n");
    /* calling our callback function my_callback */
    (*ptr_reg_callback)();                                  
}
Compile, link and run the program with gcc -Wall -o callback callback.c reg_callback.c and ./callback:

This is a program demonstrating function callback
inside register_callback
inside my_callback
back inside main program
The code needs a little explanation. Assume that we have to call a callback function that does some useful work (error handling, last-minute clean-up before exiting, etc.), after an event occurs in another part of the program. The first step is to register the callback function, which is just passing a function pointer as an argument to some other function (e.g., register_callback) where the callback function needs to be called.
We could have written the above code in a single file, but have put the definition of the callback function in a separate file to simulate real-life cases, where the callback function is in the top layer and the function that will invoke it is in a different file layer. So the program flow is like what can be seen in Figure 1.


Figure 1: Program flow

The higher layer function calls a lower layer function as a normal call and the callback mechanism allows the lower layer function to call the higher layer function through a pointer to a callback function.
This is exactly what the Wikipedia definition states.

Use of callback functions

One use of callback mechanisms can be seen here:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/ * This code catches the alarm signal generated from the kernel
    Asynchronously */
#include
#include
#include
struct sigaction act;
/* signal handler definition goes here */
void sig_handler(int signo, siginfo_t *si, void *ucontext)
{
   printf("Got alarm signal %d\n",signo);
   /* do the required stuff here */
}
int main(void)
{
    act.sa_sigaction = sig_handler;
    act.sa_flags = SA_SIGINFO;
    /* register signal handler */
    sigaction(SIGALRM, &act, NULL);  
    /* set the alarm for 10 sec */       
    alarm(10);   
    /* wait for any signal from kernel */                                        
    pause();  
    /* after signal handler execution */                                             
    printf("back to main\n");                     
    return 0;
}
Signals are types of interrupts that are generated from the kernel, and are very useful for handling asynchronous events. A signal-handling function is registered with the kernel, and can be invoked asynchronously from the rest of the program when the signal is delivered to the user process. Figure 2 represents this flow.

Figure 2: Kernel callback

Callback functions can also be used to create a library that will be called from an upper-layer program, and in turn, the library will call user-defined code on the occurrence of some event. The following source code (insertion_main.c, insertion_sort.c and insertion_sort.h), shows this mechanism used to implement a trivial insertion sort library. The flexibility lets users call any comparison function they want.

1
2
3
4
/* insertion_sort.h */
typedef int (*callback)(int, int);
void insertion_sort(int *array, int n, callback comparison);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
/* insertion_main.c */
#include
#include
#include"insertion_sort.h"
int ascending(int a, int b)
{
    return a > b;
}
int descending(int a, int b)
{
    return a < b;
}
int even_first(int a, int b)
{
    /* code goes here */
}
int odd_first(int a, int b)
{
    /* code goes here */
}
int main(void)
{
    int i;
    int choice;
    int array[10] = {22,66,55,11,99,33,44,77,88,0};
    printf("ascending 1: descending 2: even_first 3: odd_first 4: quit 5\n");
    printf("enter your choice = ");
    scanf("%d",&choice);
    switch(choice)
    {
        case 1:
            insertion_sort(array,10, ascending);
            break;
        case 2:
            insertion_sort(array,10, descending);
         case 3:
            insertion_sort(array,10, even_first);
            break;
        case 4:
            insertion_sort(array,10, odd_first);
            break;
        case 5:
            exit(0);
        default:
            printf("no such option\n");
    }
    printf("after insertion_sort\n");
    for(i=0;i<10 code="" i="">
        printf("%d\t", array[i]);
    printf("\n");
     return 0;
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/* insertion_sort.c */
#include"insertion_sort.h"
void insertion_sort(int *array, int n, callback comparison)
{
    int i, j, key;
    for(j=1; j<=n-1;j++)
    {
        key=array[j];
        i=j-1;
        while(i >=0 && comparison(array[i], key))
        {
            array[i+1]=array[i];
            i=i-1;
        }
        array[i+1]=key;
    }

Thursday, June 12, 2014

Memory Management In Linux OS

Paging and Swapping
The concept of virtual memory is one of the very powerful aspects of memory management. Since the initial era of computers the need of memory more than the existing physical memory has been felt. Over the years, many solutions were used to overcome this issue and the most successful of them has been the concept of virtual memory.
One basic concept in the Linux implementation of virtual memory is the concept of a page. A page is a 4Kb area of memory and is the basic unit of memory with which both the kernel and the CPU deal. Although both can access individual bytes (or even bits), the amount of memory that is managed is usually in pages.
If you are reading a book, you do not need to have all the pages spread out on a table for you to work effectively just the page you are currently using. I remember many times in college when I had the entire table top covered with open books, including my notebook. As I was studying, I would read a little from one book, take notes on what I read, and, if I needed more details on that subject, I would either go to a different page or a completely different book.
Virtual memory in Linux is very much like that. Just as I only need to have open the pages I am working with currently, a process needs to have only those pages in memory with which it is working. Like me, if the process needs a page that is not currently available (not in physical memory), it needs to go get it (usually from the hard disk).

If another student came along and wanted to use that table, there might be enough space for him or her to spread out his or her books as well. If not, I would have to close some of my books (maybe putting bookmarks at the pages I was using). If another student came along or the table was fairly small, I might have to put some of the books away. Linux does that as well. Imagine that the text books represent the unchanging text portion of the program and the notebook represents the changing data which might make things a little clearer.
It is the responsibility of both the kernel and the CPU to ensure that I don't end up reading someone else's textbook or writing in someone else's notebook. That is, both the kernel and the CPU ensure that one process does not have access to the memory locations of another process (a discussion of cell replication would look silly in my calculus notebook). The CPU also helps the kernel by recognizing when the process tries to access a page that is not yet in memory. It is the kernel's job to figure out which process it was, what page it was, and to load the appropriate page.

It is also the kernel's responsibility to ensure that no one process hogs all available memory, just like the librarian telling me to make some space on the table. If there is only one process running (not very likely), there may be enough memory to keep the entire process loaded as it runs. More likely is the case in which dozens of processes are in memory and each gets a small part of the total memory. (Note: Depending on how much memory you have, it is still possible that the entire program is in memory.)
Processes generally adhere to the principle of spatial locality. This means that typically processes will access the same portions of their code over and over again. The kernel could establish a working set of pages for each process, the pages that have been accessed with the last n memory references. If n is small, the processes may not have enough pages in memory to do their job. Instead of letting the processes work, the kernel is busy spending all of its time reading in the needed pages. By the time the system has finished reading in the needed pages, it is some other process's turn. Now, some other process needs more pages, so the kernel needs to read them in. This is called thrashing. Large values of n may lead to cases in which there is not enough memory for all the processes to run.
The solution is to use a portion of hard disk as a kind of temporary storage for data pages that are not currently needed. This area of the hard disk is called the swap space or swap device and is a separate area used solely for the purpose of holding data pages from programs.
The size and location of the swap device is normally set when the system is first installed. Afterward, more swap space can be added if needed. (Swap space is added with the mkswap command and the system is told to use it with the swapon command.)
Eventually, the process that was swapped out will get a turn on the CPU and will need to be swapped back in. Before it can be swapped back in, the system needs to ensure that there is at least enough memory for the task structure and a set of structures called page tables. Page tables are an integral part of the virtual memory scheme and point to the actual pages in memory. I talk more about this when I talk about the CPU in the hardware section.
Often you don't want to swap in certain pages. For example, it doesn't make sense to swap in pages for a process that is sleeping on some event. Because that event hasn't occurred yet, swapping them in means that it will just need to go right back to sleep. Therefore, only processes in the TASK_RUNNING state are eligible to have pages swapped back in. That is, only the processes that are runnable get pages swapped back in.
Keep in mind that accessing the hard disk is hundreds of times slower than accessing memory. Although swapping does allow you to have more programs in memory than the physical RAM will allow, using it slows down the system. If possible, it is a good idea to keep from swapping by adding more RAM.
Until kernel 2.3.24 on the x86 platform, the Linux memory manager limited the size of each swap area to 127.5 MB. You could have created a larger swap space, but only the first 127.5 MB will be used. To solve this limitation, a system could have had up to 16 swap spaces for a total of 2GB in swap space. Now Linux supports up to 64 GB of physical memory and several TB of swap.

Demand Paging

As there is much less physical memory than virtual memory the operating system must be careful that it does not use the physical memory inefficiently. One way to save physical memory is to only load virtual pages that are currently being used by the executing program. For example, a database program may be run to query a database. In this case not all of the database needs to be loaded into memory, just those data records that are being examined. If the database query is a search query then it does not make sense to load the code from the database program that deals with adding new records. This technique of only loading virtual pages into memory as they are accessed is known as demand paging.
When a process attempts to access a virtual address that is not currently in memory, the processor cannot find a page table entry for the virtual page being referenced. At this point the processor notifies the operating system that a page fault has occurred.
If the faulting virtual address is invalid this means that the process has attempted to access a virtual address that it should not have. Maybe the application has gone wrong in some way, for example writing to random addresses in memory. In this case the operating system will terminate it, protecting the other processes in the system from this rogue process.
If the faulting virtual address was valid but the page that it refers to is not currently in memory, the operating system must bring the appropriate page into memory from the image on disk. Disk access takes a long time, relatively speaking, and so the process must wait quite a while until the page has been fetched. If there are other processes that could run, then the operating system will select one of them to run. The fetched page is written into a free physical page frame and an entry for the virtual page frame number is added to the process' page table. The process is then restarted at the machine instruction where the memory fault occurred. This time the virtual memory access is made, the processor can make the virtual to physical address translation and so the process continues to run.
Linux uses demand paging to load executable images into a process's virtual memory. Whenever a command is executed, the file containing it is opened and its contents are mapped into the process's virtual memory. This is done by modifying the data structures describing this process' memory map and is known as memory mapping. However, only the first part of the image is actually brought into physical memory. The rest of the image is left on disk. As the image executes, it generates page faults and Linux uses the process's memory map in order to determine which parts of the image to bring into memory for execution.

Swapping

If a process needs to bring a virtual page into physical memory and there are no free physical pages available, the operating system must make room for this page by discarding another page from physical memory.
If the page to be discarded from physical memory came from an image or data file and has not been written to then the page does not need to be saved. Instead it can be discarded and brought back into memory from the original image or data file if it is needed again.
However, if the page has been modified, the operating system must preserve the contents of that page so that it can be accessed at a later time. This type of page is known as a dirty page. When dirty pages are removed from memory, they are saved in a special sort of file called the swap file. Since access to the swap file takes a long time relative to the speed of the processor and physical memory, the operating system must juggle the need to write pages to disk with the need to retain them in memory.
If the swap algorithm, which is used to decide which pages to discard or swap is not efficient, then a condition known as thrashing occurs. In the case of thrashing, pages are constantly being written to and read back from disk.  This causes the operating system to be too busy to perform enough real work
Linux uses a Least Recently Used (LRU) page aging technique to fairly choose pages which might be removed from the system. This scheme involves every page in the system having an age which changes as the page is accessed. The more that a page is accessed, the younger it is; the less that it is accessed, the older and more stale it becomes. Old pages are good candidates for swapping.

Tuesday, June 10, 2014

How to add your linux driver module in a kernel

Use below steps to add your driver module in linux kernel. by adding your driver as a module you can load/unload it at your convenience and will not be a part of your kernel image. I have used hello driver to explain it.
Steps to follow
===========
1). Create your module directory in /kernel/drivers
Eg. mkdir hellodriver
2).  Create your file inside /kernel/drivers/hellodriver/  and add below functions and save it.
Write your driver init and exit function in hello.c file.
————————————————–
#include
#include
static int __init hello_module_init(void)
{
printk (“hello test app module init”);
return 0;
}
static int __exit hello_module_cleanup(void)
{
printk(“hello test app module cleanup “);
return 0;
}
module_init(hello_module_init);
module_exit(hello_module_cleanup);
MODULE_LICENSE(“GPL”);
—————————————————————————————-
3).  Create empty Kconfig file and Makefile in /kernel/drivers/hellodriver/
4). Add below entries in Kconfig
config HELLOTEST_APP
tristate “HelloTest App”
depends on ARM
default m
help
hellotest app
5). Add below entries in Makefile
obj-$(CONFIG_HELLOTEST_APP) +=hello.o
6). Modify the /kernel/drivers Kconfig and Makefile to support your module
7). Add below entry in /kernel/drivers/Kconfig file
source “drivers/hellodriver/Kconfig”
8). Add below entry in /kernel/drivers/Makefile file
obj-$(CONFIG_HELLOTEST_APP) +=hellodriver/
9).  Now go to kernel directory and give
make menuconfig ARCH=arm
Verify that your driver module entry is visible under Device Drivers  —>
For module entry it shows HelloTest App
Now recompile the kernel with your requirement  and give
sudo make ARCH=arm CROSS_COMPILE=your toolchain path-
10). Check the hello.o and hello.ko files are generated at /kernel/drivers/hellodriver/
If you want to make your module as a part of kernel image then you only need to change <*> HelloTest App the option in menuconfig and  recompile the kernel.
If you don’t want to make your module as a part of kernel image then you only need to change <> HelloTest App the option in menuconfig and  recompile the kernel.
This is a very simple example of adding a module in a kernel.
How to Load/Unload  module/s from the user space:
In user space, you can load the module as root by typing the following into the command line. insmod load the module into kernel space.
# insmod hello.ko

To see the module loaded you can do following:

# lsmod

To remove your module from the kernel space you can do followig:

#rmmod hello.ko

Sunday, June 8, 2014

C++ Interview Question and Answer

Define structured programming.


Structured programming techniques use functions or subroutines to organize the programming code. The programming purpose is broken into smaller pieces and organized together using function. This technique provides cleaner code and simplifies maintaining the program. Each function has its own identity and isolated from other, thus change in one function doesn’t affect other. 


Explain Object oriented programming.
Object oriented programming uses objects to design applications. This technique is designed toisolate data. The data and the functions that operate on the data are combined into single unit. This unit is called an object. Each object can have properties and member functions. You can call member function to access data of an object. It is based on several techniques like encapsulation, modularity, polymorphism, and inheritance.



List down elements of an object oriented language.

Class

A class is a user defined data type. It serves as a template of the objects. You can definestructure and behavior of an object using class. It includes data and the member functions thatoperate on data.

Inheritance

Inheritance enables a new class to reuse the state and behavior of old class. The new class inherits properties and methods from the old class and is called as derived class and the old class is called as base class. The methods thus inherited can be extended using overriding facility of C++.

Encapsulation

The wrapping up of data and member function into an object is called encapsulation. The data is not accessible to the outside world and only those functions which are wrapped into the object can access it. An encapsulated objects act as a "black box" for other parts of the program which interact with it. They provide a service, but the calling objects do not need to know the details how the service is accomplished.

Polymorphism

Polymorphism enables one common interface for many implementations that allows objects to act differently under different circumstances. You can also achieve polymorphism in C++ by function overloading, operator overloading and implementation inheritance. 

What is function prototype in C++?
A function prototype is a declaration of a function that omits the function body. It specifies the function’s name, argument types and return type. E.g. int add(int,int) 


What are the ways to comment statement in C++? 

  
/* */ is used for commenting a block of code. 

// is used for single line comments. 
Define Structure in C++.

The C++ programming technique allows defining user defined datatypes through structure. The 

syntax to declare structure is as follows: 

struct student 



char name[100] 

char address[250] 

}; 
Explain typecasting.


Typecasting enables data type conversion. C++ supports implicit conversions and explicit conversion. Implicit conversions automatically performed when a value is copied to a compatible type. If there is an operation between an int and a float, the int is promoted to float before performing operation automatically by the compiler. 

You can cast explicitly as follows. 

int i, j, k; 

k = i * long(j); 


Define void pointer using C++.


In C++, void represents the absence of type, so void pointers are pointers that point to a value that has no type. The void pointers can point to any data type. 

You can declare void pointer as follows. 

void *p; 


When do you use :: Operator in C++?
:: is the scope resolution operator. When local variable and global variable are having same name, local variable gets the priority. C++ allows flexibility of accessing both the variables through a scope resolution operator. 

Define reference variable in C++.
A reference variable is just like pointer with few differences. It is declared using & operator. A reference variable must always be initialized. The reference variable once defined to refer to a variable can’t be changed to point to other variable. You can’t create an array of references the way it is possible with pointer.

What is const qualifier?
const qualifier is used to specify the variable that can’t be change throughout the program. Variables with const qualifier are often named in uppercase.

When do you use bool data type?
The bool data type can take only two values true or false.

What is function overloading in C++?


You can have multiple functions with same name using function overloading facility of C++. You can use same name for multiple functions when all these functions are doing same thing. 

What is operator overloading in C++?
With this facility in C++, you can give additional meaning to operators. 


Define Inline Function.


When the function is defined Inline, the C++ compiler puts the function body inside the calling function. You can define function as Inline when the function body is small and need to be called  many times, thus reduces the overhead in calling a function like passing values, passing control,returning values, returning control. 


Define class using C++.
A class holds the data and functions that operate on the data. It serves as the template of an object. 

Explain constructors and destructors.


Constructors are the member functions of the class that executes automatically whenever anobject is created. Constructors have the same name as the class. Constructors initialize the class. Constructors can’t have return type. Destructors are called when the objects are destroyed. 

Destructors are usually used to deallocate memory and do other cleanup for a class object and its class members when the object is destroyed. A destructor is called for a class object when that  object passes out of scope or is explicitly deleted. A destructor takes no arguments and has no return type. 


When do you use this pointer?
’this pointer’ is used as a pointer to the class object instance by the member function. The address of the class instance is passed as an implicit parameter to the member functions. 

What is new and delete operator?

In C++, when you want dynamic memory, you can use operator new. It returns a pointer to the beginning of the new block of memory allocated. It returns a pointer to the beginning of the new block of memory allocated. When memory allocated by new operator is no longer required, it is freed using operator delete. 



Explain the difference between structures and classes.
Syntactically and functionally, both structures and classes are identical. By default, members of structures have public accessibility and public inheritance from their parent(s), while members of classes are private and inherit privately from their parent(s). 


Define local class in C++.


Local class is define within the scope of a function and nested within a function. 

E.g. 

int func1() 



class localclass1 



}; 



Explain container class and its types in C++.
A container stores many entities and provide sequential or direct access to them. List, vector and strings are such containers in standard template library. The string class is a container that holds chars. All container classes access the contained elements safely and efficiently by using iterators. Container class is a class that hold group of same or mixed objects in memory. It can be heterogeneous and homogeneous. Heterogeneous container class can hold mixed objects in memory whereas when it is holding same objects, it is called as homogeneous container class. 


Define an Iterator class.


A container class hold group of objects and iterator class is used to traverse through the objects maintained by a container class. The iterator class provides access to the classes inside a container. They are objects that point to other objects. Iterator points to one element in a range, and then it is possible to increment it so that it points to the next element. 

There are several different types of iterators: 

input_iterator 

output_iterator 

forward_iterator 

bidirectional_iterator 

random_iterator 

reverse_iterator 


Define storage classes in C++.


Storage class defined for a variable determines the accessibility and longevity of the variable. The accessibility of the variable relates to the portion of the program that has access to the variable. The longevity of the variable refers to the length of time the variable exists within the program. 

Auto 

Automatic variable, also called as local variable and it has scope only within the function block where it is defined. 

External 

External variable are defined outside any function and memory is set aside for this type of variable once it is declared and remained until the end of the program. These variables are also called global variables. 

Static 

The static automatic variables, as with local variables, are accessible only within the function in which it is defined. Static automatic variables exist until the program ends in the same manner as 

external variables. In order to maintain value between function calls, the static variable takes its presence. 


Define namespace in C++.
Namespaces groups together entities like classes, objects and functions under a name. Namespaces provide a way to avoid name collisions of variables, types, classes or functions. Namespaces reduces the use of nested class thus reduces the inconvenience of handling nested class. 

Define access privileges in C++.


You have access privileges in C++ such as public, protected and private that helps in encapsulation of data at various level. 

Private 

If data are declared as private in a class then it is accessible by the member functions of the class where they are declared. The private member functions can be accessed only by the members of 

the class. By default, any member of the class is considered as private by the C++ compiler, if no specifier is declared for the member. 

Public 

The member functions with public access specifier can be accessed outside of the class. This kind of members is accessed by creating instance of the class. 

Protected 

Protected members are accessible by the class itself and it’s sub-classes. The members with protected specifier act exactly like private as long as they are referenced within the class or from 

the instance of the class. This specifier specially used when you need to use inheritance facility of C++. The protected members become private of a child class in case of private inheritance, public in case of public inheritance, and stay protected in case of protected inheritance. 


What is the default access level?
The access privileges in C++ are private, public and protected. The default access level assigned to members of a class is private. Private members of a class are accessible only within the class and by friends of the class. Protected members are accessible by the class itself and its subclasses. Public members of a class can be accessed by anyone. 

Explain friend class in C++.
When a class declares another class as its friend, it is giving complete access to all its data and methods including private and protected data and methods to the friend class member methods. Friendship is one way only, which means if A declares B as its friend it does NOT mean that A can access private data of B. It only means that B can access all data of A.

What is virtual function?
Virtual function is the member function of a class that can be overriden in its derived class. It is declared with virtual keyword. Virtual function call is resolved at run-time (dynamic binding) whereas the non virtual member functions are resolved at compile time (static binding).

What are pure virtual functions?

Pure virtual function is the function in the base class with no body. Since no body, you have to add the notation =0 for declaration of the pure virtual function in the base class. 

The base class with pure virtual function can’t be instantiated since there is no definition of the function in the base class. It is necessary for the derived class to override pure virtual function. 

This type of class with one or more pure virtual function is called abstract class which can’t be instantiated, it can only be inherited. 

class shape 



public: virtual void draw() = 0; 

}; 


Define default constructor.


Default constructor is the constructor with no arguments or all the arguments has default values. Define abstraction. The process of hiding unnecessary data and exposing essential features is called abstraction. Abstraction is separating the logical properties from implementation details. 



What is overriding?
Defining a function in the derived class with same name as in the parent class is called overriding. In C++, the base class member can be overridden by the derived class function with the same signature as the base class function. Method overriding is used to provide different implementations of a function so that a more specific behavior can be realized. 


What is copy constructor?

A copy constructor is a special type of constructor that is used to create an object as a copy of an existing object. It takes an argument which is a reference to the object to be copied.