Tag Archives: storage classes

C++ concise cheat sheet on operators, malloc, calloc, storage classes, and storage qualifiers

C++ concise cheat sheet on operators, malloc, calloc, storage classes, and storage qualifiers

Operators
What is assignment operator?
Default assignment operator handles assigning one object to another of the same class. Member to member copy (shallow copy)
What is conversion operator??
class can have a public method for specific data type conversions.
for example:
class Boo
{
double value;
public:
Boo(int i )
operator double() { return value; ]
};
Boo BooObject;
double i = BooObject; // assigning object to variable i of type double. now conversion operator gets called to assign the value.
The postfix version of operator++() has a dummy parameter of type int. The prefix version does not have dummy parameter.
What are all the implicit member functions of the class? Or what are all the functions which compiler implements for us if we don’t define one.?? default ctor, copy ctor, assignment operator, default destructor, address operator
Memory Related

New and delete allocate memory. New calls constructor while malloc does not.
Reference: has to be initialized when declared
cannot reseat once refer to an object
cannot do arithmetic operation, int& ref=&a, ref++ will be wrong
cannot be assigned with NULL
cannot take the reference of a reference variable, pointter of pointer is possible
As a general rule,
Use references in function parameters and return types to define attractive interfaces.
Use pointers to implement algorithms and data structures.

Hard/Deep Copy is copying the values from one structure to another.If there are pointers in the structure, then the second structure also points to the same pointer location as in the first one. To make a hard copy, you must wite a copy constructor and overload the assignment operator.

Shallow copy is copying bit by bit, If there are pointers in the structure to be copied,then a new memory location is created and data is copied to that location.

Note that calloc has 2 arguments while there is 1 in malloc.
void *malloc( size_t size ); void * calloc ( size_t num, size_t size );.

Malloc reduces requesting new memory from OS by recycling the freed memory space. It uses Free List to keep track of the freed memory. When free(ptr) is called, the allocator looks at the header/footer of the memory block. The header of the memory block contains enough information (such as total bytes, status(freed/allocated), etc..) to remove it. ) This free list needs not to be a single linked list generally a balanced tree .

Why should malloc never be directly used to dynamically allocate instances of a class?

malloc just allocates memory for objsize* but it doesn’t initialize the class (i.e invoking constructor and performing initialization). whereas “new” allocates the memory for the objsize* and implicit invoke the constructor (in case no constructor exist, then default is considered) to initialize the class.
What is diff between malloc()/free() and new/delete?
malloc allocates memory for object in heap but doesn’t invoke object’s constructor to initiallize the object.
new allocates memory and also invokes constructor to initialize the object.
malloc() and free() do not support object semantics
Does not construct and destruct objects
string * ptr = (string *)(malloc (sizeof(string)))
Are not safe
Does not calculate the size of the objects that it construct
Returns a pointer to void
int *p = (int *) (malloc(sizeof(int)));
int *p = new int;
Are not extensible
new and delete can be overloaded in a class
“delete” first calls the object’s termination routine (i.e. its destructor) and then releases the space the object occupied on the heap memory. If an array of objects was created using new, then delete must be told that it is dealing with an array by preceding the name with an empty []:-
Int_t *my_ints = new Int_t[10];

delete []my_ints;

Char a[]=””; is size of 2 characters which is ‘\0’ and null. The trick is the memory allocated two characters of space. Char a[]=”hello”; // 6 bytes
Char *a=”hello”; //4 bytes

IF we are decreasing the size of vector, or if we are increasing the size but the vector still has enough capacity, there’s no need to allocate memory. When capacity is not enough, the function will cause a reallocation: 1). allocate contiguous memory elsewhere, which can hold the original vector plus new elements. if such a space is not available, return false; 2) copy the original vector and then reclaim the space; 3) add new elements at the back. Sorry, when reallocation is not successful, this function will not return a false, it’s a void function. Instead, a bad_alloc exception will be thrown.
Memory allocation depends on ‘best fit’ and ‘first fit’.
Stack:
– local variables (variables declared inside a function) are put on the stack – unless they are also declared as ‘static’ or ‘register’
– function parameters are allocated on the stack
– local variables that are declared on the stack are not automatically initialized by the system so they usually have garbage in them until you set them
– variables on the stack disappear when the function exits (thus, if a function is called multiple times, it’s local variables and parameters are recreated and destroyed each time the function is called end exited).
Heap:
– declared variables (as opposed to dynamically created ie new, malloc) are created on the heap before program execution begins, they exist the entire life of the program (although scope may prevent access to them – they still exist) and they are initialized to all zeros
– global variables are on the heap
– static local variables are on the heap (this is how they keep their value between function calls)
– memory allocated by new, malloc and calloc are on the heap
Code Segment
Data Segment:
– Unintialized Data (bss block started by symbol) – Static variables (before program initializes, these variables will be initialized zero.
– initilaized Data (your int i =0)
Templates
template
T sum(T* arr, int num){

T sum=0;
for(int i=0;i
int Product (T1 a, T2 b, T3 c) { return a * b * c; }
You cannot return an int since the parameter is type T, you do not know if it is an int, so you must return a type T.
Storage classes and storage qualifiers
auto
register
static
extern
auto: the default. Variables are automatically created and initialized when they are defined and are destroyed at the end of the block containing their definition. They are not visible outside that block
register: a type of auto variable. a suggestion to the compiler to use a CPU register for performance
static: a variable that is known only in the function that contains its definition but is never destroyed and retains its value between calls to that function. It exists from the time the program begins execution
extern: a static variable whose definition and placement is determined when all object and library modules are combined (linked) to form the executable code file. It can be visible outside the file where it is defined.
What are storage qualifiers in C++ ?
They are..
const
volatile
mutable
Const keyword indicates that memory once initialized, should not be altered by a program.
volatile keyword indicates that the value in the memory location can be altered even though nothing in the program
code modifies the contents. for example if you have a pointer to hardware location that contains the time, where hardware changes the value of this pointer variable and not the program. The intent of this keyword to improve the optimization ability of the compiler.
mutable keyword indicates that particular member of a structure or class can be altered even if a particular structure variable, class, or class member function is constant.
struct data
{
char name[80];
mutable double salary;
}
const data MyStruct = { “Satish Shetty”, 1000 }; //initlized by complier
strcpy ( MyStruct.name, “Shilpa Shetty”); // compiler error
MyStruct.salaray = 2000 ; // complier is happy allowed

NOTE I now post my TRADING ALERTS into my personal FACEBOOK ACCOUNT and TWITTER. Don't worry as I don't post stupid cat videos or what I eat!

C++ interview questions on storage classes like static, register, auto, extern, volatile, mutable

C++ interview questions on storage classes like static, register, auto, extern, volatile, mutable

Storage classes
What are C++ storage classes?
auto
register
static
extern
auto: the default. Variables are automatically created and initialized when they are defined and are destroyed at the end of the block containing their definition. They are not visible outside that block
register: a type of auto variable. a suggestion to the compiler to use a CPU register for performance
static: a variable that is known only in the function that contains its definition but is never destroyed and retains its value between calls to that function. It exists from the time the program begins execution
extern: a static variable whose definition and placement is determined when all object and library modules are combined (linked) to form the executable code file. It can be visible outside the file where it is defined.
What are storage qualifiers in C++ ?
They are..
const
volatile
mutable
Const keyword indicates that memory once initialized, should not be altered by a program.
volatile keyword indicates that the value in the memory location can be altered even though nothing in the program
code modifies the contents. for example if you have a pointer to hardware location that contains the time, where hardware changes the value of this pointer variable and not the program. The intent of this keyword to improve the optimization ability of the compiler.
mutable keyword indicates that particular member of a structure or class can be altered even if a particular structure variable, class, or class member function is constant.
struct data
{
char name[80];
mutable double salary;
}
const data MyStruct = { “Satish Shetty”, 1000 }; //initlized by complier
strcpy ( MyStruct.name, “Shilpa Shetty”); // compiler error
MyStruct.salaray = 2000 ; // complier is happy allowed

Reference:

What’s the difference between pointer and reference
Reference is to one object can not be changed to another object
Reference should be initialized always.
Any other Differences??

NOTE I now post my TRADING ALERTS into my personal FACEBOOK ACCOUNT and TWITTER. Don't worry as I don't post stupid cat videos or what I eat!