Showing posts with label Cpp. Show all posts
Showing posts with label Cpp. Show all posts

Thursday, October 04, 2012

Another way of adding NDK logs in C/C++:

#include
LOCAL_LDLIBS := -llog

void LOGI(char *szMsg)
{
__android_log_write(ANDROID_LOG_ERROR,"Tag",szMsg);
}
 Read and print all arguments in C/C++:
===========================
     
  int count;
   for (count = 0; count < argc; count++)
   {
            printf ("%s\n", argv[count]);
   }

Wednesday, August 01, 2007

Comma Testing

Comma Can be used as a separator in C++ program , Look at the sample application :



void CommaTesting()

{



int a,int b;



a= 20,b = 20;



printf("\n Value of a = %d \t b = %d",a,b);

}



int main(int argc, char* argv[])

{



CommaTesting();

return 0;

}



the Output is :



Value of a = 10 b = 20

Tuesday, July 10, 2007

Hi ,


I faced the problem in C++ class as follows :

error C2533: 'VideoQualityUtil::__ctor' : constructors not allowed a return type

VideoQualityUtil::VideoQualityUtil()
{
m_pVideoQualityTool = NULL;
m_pCsvWriter = NULL;
}
So I refered the MSDN documentation for the Error C2533.

MSDN documentation for Error C2533 :


'identifier' : constructors not allowed a return type

A constructor cannot a value or have a return type (not even a void return type).

The following sample generates C2533:

// C2533.cpp

class X

{

public:

X();

};


int X::X()

// try the following line instead

// X::X()

{ // C2533

}


int main()

{

}




Can U identify where my program failed ?....


Scroll to see the Answer ...


.

.

.



Answer :

Sometimes with the help of MSDN, we can't solve the errors...




I found where my code fails...I left the class as follows...




class VideoQualityUtil

{

}


we have to change it as follows :



class VideoQualityUtil

{

}

;

I missed the semi colon...

Wednesday, June 20, 2007

Address Increment with the help of sizeof() operator

int * x = new int[10];
x++; //it will increments the pointer by 2 bytes


char* y = new char[10];
x++; // it will increments the pointer by 1 byte


How pointers are moved during address addition or address subtraction operation ?


they will use sizeof() operator to find the size of it and added it.


For Example

int * x = new int[10];
++x;

can't invoke a non-const member function on a const object

we can't invoke a non-const member function on a const object....


Example :

class CTest
{
public:
CTest() { }
~CTest() { }

void Exam() { }
void Exam2() const { }

};


void f( const CTest testObj)
{
testObj.Exam() ; // Will cause an Error , we are invoking a non-const member function in a const object

}






Invoking a non-const member function on a const object.
Possible solutions
Remove the const from the object declaration.
Add const to the member function.


Example
// C2662.cpp
class C
{
public:
void func1();
void func2() const;
} const c;

int main()
{
c.func1(); // C2662
c.func2(); // no error
}

Tuesday, June 19, 2007

Lvalues and RValues

lvalues and rvalues
----------------------------------

An object is a contiguous region of storage. An lvalue is an expression that refers to such an object. The original

definition of lvalue referred to an object that can appear on the left-hand side of an assignment. However, const

objects are lvalues that cannot be used in the left-hand side of an assignment. Similarly, an expression that can appear

in the right-hand side of an expression (but not in the left-hand side of an expression) is an rvalue. For example


#include

using namespace std;

int& f();

void func()

{

int n;

char buf[3];

n = 5; // n is an lvalue; 5 is an rvalue

buf[0] = 'a'; // buf[0] is an lvalue, 'a' is an rvalue

string s1 = "a", s2 = "b", s3 = "c"; // "a", "b", "c" are rvalues

s1 = // lvalue

s2 +s3; //s2 and s3 are lvalues that are implicitly converted to rvalues

s1 = //lvalue

string("z"); //temporaries are rvalues

int * p = new int; //p is an lvalue; 'new int' is an rvalue

f() = 0; //a function call that returns a reference is an lvalue

s1.size(); //otherwise, a function call is an rvalue expression

}

An lvalue can appear in a context that requires an rvalue; in this case, the lvalue is implicitly converted to an rvalue.

An rvalue cannot be converted to an lvalue. Therefore, it is possible to use every lvalue expression in the example as an rvalue, but not vice versa.

Thursday, June 14, 2007

mutable keyword

mutable keyword :
-----------------------
Class member functions may be declared as const, which causes this to be treated as a
const pointer. Thus, that function cannot modify the object that invokes it. Also, a const
object may not invoke a non-const member function. However, a const member
function can be called by either const or non-const objects.

within const member fns we can' change the value. In C++ we can change the value using mutable keyword.

class X
{
int i;
public:
int f1() const; // const member function
};


int X::f1() const
{

i = 10; // This will gives error because we are trying to modify the value in a const member function

return i;
}

we can modify the values if we use the mutable keyword. Following code will works...

This is the concept of mutable in C++.



class X
{
mutable int i;
public:
int f1() const; // const member function
};


int X::f1() const
{

i = 10; // This will gives error because we are trying to modify the value in a const member function

return i;
}

Tuesday, June 12, 2007

Real use of BitFields

Bit-Fields


C/C++ has a built-in feature called a bit-field
that allows you to access a single bit. Bit-fields can be useful for a number of reasons,
such as:
1. If storage is limited, you can store several Boolean (true/false) variables in
one byte.
2. Certain devices transmit status information encoded into one or more bits
within a byte.
3.Certain encryption routines need to access the bits within a byte.


To access individual bits, C/C++ uses a method based on the structure.
The general form of a bit-field definition is

struct struct-type-name {
type name1 : length;
type name2 : length;
..
.
type nameN : length;
} variable_list;

Here, type is the type of the bit-field and length is the number of bits in the field.
A bit-field must be declared as an integral or enumeration type. Bit-fields of length
1 should be declared as unsigned, because a single bit cannot have a sign.
Bit-fields are frequently used when analyzing input from a hardware device.
For example, the status port of a serial communications adapter might return a
status byte organized like this:


Bit Meaning When Set
0 Change in clear-to-send line
1 Change in data-set-ready
2 Trailing edge detected
3 Change in receive line
4 Clear-to-send
5 Data-set-ready
6 Telephone ringing
7 Received signal


You can represent the information in a status byte using the following bit-field:


struct status_type {
unsigned delta_cts: 1;
unsigned delta_dsr: 1;
unsigned tr_edge: 1;
unsigned delta_rec: 1;
unsigned cts: 1;
unsigned dsr: 1;
unsigned ring: 1;
unsigned rec_line: 1;
} status;
You might use a routine similar to that shown here to enable a program to determine
when it can send or receive data.


status = get_port_status();
if(status.cts) printf("clear to send");
if(status.dsr) printf("data ready");


To assign a value to a bit-field, simply use the form you would use for any other type
of structure element. For example, this code fragment clears the ring field:

status.ring = 0;

Monday, June 11, 2007

Operator Keywords

ANSI C++ introduced the operator keywords :

C++ suggested to use the following key words for any operation.

operator operator Keywords Description

&& and logical AND

|| or logical OR

! not logical NOT

!= not_eq Inequality

& bitand bitwise and

| bitor bitwise or

^ xor bitwise xor

~ compl complement operator

&= and_eq bitwise AND assignement

|= or_eq bitwise OR assignement

^= xor_eq bitwise XOR assignement



Example program :
=================

The following example program is compiled in microsoft visual C++
win32 console application.


#include

int main(int argc, char* argv[])
{

int i = 0;
int j = 20;
printf("Hello World! : %d", i and j);
return 0;
}


Note the program, I used the "and" operator keyword. In that way we can access the

operators listed above.

Friday, June 08, 2007

__FILE__, __LINE__ and __cplusplus macro

we often meet the __FILE__ macro in an MFC application. it seems MFC macro.But it is one of the c++ predefined macro. __FILE__ macro is available in C++ . __LINE__ macro is also available in C++.


__FILE__ & __LINE__ macros specified in C & C++ standards are useful to provide some debugging information, during run-time. During pre-processing stage of compilation,

__FILE__ macro expands to the name of the file being compiled, in the form of a C string constant;
__LINE__ expands to the line number of the source file that is being compiled, in the form of an integer constant.




Simple Example with them :
-----------------------------------

Filename is "C:\MacroTesting.cpp"
-------------------------------------------

#include
#include

int main(int argc, char **argv)
{
FILE *fd;

char errinfo[100];

fd = fopen ("C:\Test.txt" , "r");
if (fd == NULL)
{
sprintf (errinfo, "Error at line %d of %s", (__LINE__ - 3), __FILE__);
perror (errinfo);
free (errinfo);
}
else
{
printf ("file descriptor = %d", fileno(fd));
fclose (fd);
}

return (0);
}



In the above program we are opening "C:\test.txt" in read mode.

if the file is not available, then it will displays error as follows :

Output :

Error at line 14 of C:\MacroTesting.cpp

This will be very useful for identifying errors in an application ( if the application has so many files at that time it will be very

useful to identify where the program failed...)





__cpluscplus macro C++
----------------------------------


#ifdef __cplusplus
extern "C" {
#endif

DECLARE_INTERFACE_(IHistogram, IUnknown)
{

STDMETHOD(GetParams) (THIS_ HistogramParams *irp ) PURE;

};

#ifdef __cplusplus
}
#endif

Thursday, June 07, 2007

constant qualifier testing

Const qualifier test application

#include
void ConstTesting()
{
char* const ptr1 = "Good"; //address is constant
char* s = "sundar";
ptr1 = s; //will be in an error because address is constant


int m = 10;
int const *ptr2 = &m; //content is constant
*ptr2 = *ptr2 + 2; //the content is constant so this will gives error



const char* const cp = "xyz"; //Both address and content is constant

cp = s; //address is constant so this will gives me error

strcpy(cp,"sundar"); //content is constant so this will also gives error







}

int main(int argc, char* argv[])
{
ConstTesting();
return 0;
}

cpp tips

various usage of const keyword with variable:


1.char* const ptr1 ="Good";

2.int const *ptr2 = &m ; //content is constant

3.const char* const cp = "xyz" ; //Both address and content is constant



can u differentiate the above three usage ?

...

Ans :

1.char* const ptr1 ="Good"; //address is constant

2.int const *ptr2 = &m ; //content is constant

3.const char* const cp = "xyz" ; //Both address and content is constant


Is there any difference between new() and malloc() ?

new operator advantages than malloc :

1.new operator will automatically computes the size of the object.

No need to use sizeof() operator.

2.It automatically returns the correct pointer type. So there is no need to use a type cast.

3.It is possible to initialize the object while creating the memory space.

4. like any other operator, new operator can be overloaded.

Tuesday, June 05, 2007

Name mangling

Name mangling is the encoding of function and variable names into unique names so that linkers can separate common names in the language. Type names may also be mangled. The compiler generates function names with an encoding of the types of the function arguments when the module is compiled. Name mangling is commonly used to facilitate the overloading feature and visibility within different scopes. Name mangling also applies to variable names. If a variable is in a namespace, the name of the namespace is mangled into the variable name so that the same variable name can exist in more than one namespace. The C++ compiler also mangles C variable names to identify the namespace in which the C variable resides.

The scheme for producing a mangled name differs with the object model used to compile the source code: the mangled name of an object of a class compiled using one object model will be different from that of an object of the same class compiled using a different object model. The object model is controlled by compiler option or by pragma.

Name mangling is not desirable when linking C modules with libraries or object files compiled with a C++ compiler. To prevent the C++ compiler from mangling the name of a function, you can apply the extern "C" linkage specifier to the declaration or declarations, as shown in the following example:

extern "C" {
int f1(int);
int f2(int);
int f3(int);
};

This declaration tells the compiler that references to the functions f1, f2, and f3 should not be mangled.

The extern "C" linkage specifier can also be used to prevent mangling of functions that are defined in C++ so that they can be called from C. For example,

extern "C" {
void p(int){
/* not mangled */
}
};

name mangling is used in storing information about classes,templates,namespaces and operator overloading.
this means that object code produced by different compilers is not usually linkable.

Look more about name mangling :

http://en.wikipedia.org/wiki/Name_mangling

Different Style of Const in a fn

const char* GetOutputData()
{
// within this fn, we can change any values of a variable inside this fn
// and returns constant pointer, we can't modify the pointer returned by this fn
}


char* GetOutputData() const
{
//this fn will not change any values of a variable inside this fn
// and returns char* pointer, we can modify the pointer returned by this fn
}

const char* GetOutputData() const
{
//this fn will not change any values of a variable inside this fn
// and returns constant pointer, we can't modify the pointer returned by this fn

}

Monday, June 04, 2007

sample applications for Pointer to derived types and pointer to member

#include
class CConstructorThrow
{
public:
CConstructorThrow();
~CConstructorThrow();
};

CConstructorThrow::CConstructorThrow()
{
try
{
throw 100;
}
catch(...)
{
printf("\n Exception in CConstructorThrow::CConstructorThrow()...");
}

}
CConstructorThrow::~CConstructorThrow()
{

}

int main(int argc, char* argv[])
{
CConstructorThrow* pThrow = new CConstructorThrow();

if(pThrow == NULL)
{
printf("\n Constructor throw returned the null pointer ");

}
else
{
printf("constructor throw returned the valid pointer");
}
return 0;
}


I got the output as :

Exception in CConstructorThrow::CConstructorThrow()...
constructor throw returned the valid pointer








Example 2 :

Normally we

#include
#include
using namespace std;

void nothrowTesting()
{
int *p;

p = new(nothrow) int[20];

if( p == NULL)
{
printf("\n Memory allocation is failed...");
return;
}
else
{
printf("\n Memory Allocation is succeeded...");
}



if(p)
{
delete [] p;
p = NULL;
}
}


int main(int argc, char* argv[])
{
nothrowTesting();
return 0;
}


Example 3 :
-------------------------




#include
#include
using namespace std;
class nothrowClass
{
public:
nothrowClass() ;
~nothrowClass();


};

nothrowClass::nothrowClass()
{
printf("\n constructor..");
throw 100;
}

nothrowClass::~nothrowClass()
{
printf("\n destructor..");

}

void nothrowTestingClient()
{
nothrowClass* pClass;

try
{

pClass = new nothrowClass();

if(pClass == NULL)
{
printf("\n Invalid Pointer");

}
else
{

printf("\n valid Pointer");

if(pClass)
{
delete pClass;
pClass = NULL;
}


}
}
catch(...)
{
printf("\n Error in Allocation..");
}
}

int main(int argc, char* argv[])
{
nothrowTestingClient();
return 0;
}


output :
-----------
constructor
Error in Allocation (exception)
if the exception occurs the normal flow of program will be affected... So How can we handle this situation ?...

Example 4:
-------------------

#include

class Base
{
public:
Base()
{

}
~Base()
{

}

void DisplayBase()
{
printf("\n Base Display");
}


};

class Derived: public Base
{
public:
Derived()
{
}

~Derived()
{
}
void DisplayDerived()
{
printf("\n Derived Display");
}


};


int main(int argc, char* argv[])
{
Derived d;
Base* bp;

bp = &d; // we r typecasting the derived class to base class
bp->DisplayBase();

//bp->DisplayDerived() fn is an error we have to call like this...

((Derived*)bp)->DisplayDerived(); //This is the use of typecasting
return 0;
}


Example 5:
---------------------

#include

// .* and ->* are pointer to member operators

class PointerToMember
{
public:

int (PointerToMember::*fn)();

int (PointerToMember::*fn2)();

PointerToMember(int i)
{
val = i;
fn = double_val;
fn2 = double_val;

}


int val;
int double_val() { return val+val; }


int callPointer()
{
return (this->*fn)();
}





};

int main(int argc, char* argv[])
{


PointerToMember p(1); //Initialize the constructor of the class

printf("\n fn return value is : %d",p.callPointer());


return 0;
}

sample applications for Pointer to derived types and pointer to member

#include
class CConstructorThrow
{
public:
CConstructorThrow();
~CConstructorThrow();
};

CConstructorThrow::CConstructorThrow()
{
try
{
throw 100;
}
catch(...)
{
printf("\n Exception in CConstructorThrow::CConstructorThrow()...");
}

}
CConstructorThrow::~CConstructorThrow()
{

}

int main(int argc, char* argv[])
{
CConstructorThrow* pThrow = new CConstructorThrow();

if(pThrow == NULL)
{
printf("\n Constructor throw returned the null pointer ");

}
else
{
printf("constructor throw returned the valid pointer");
}
return 0;
}


I got the output as :

Exception in CConstructorThrow::CConstructorThrow()...
constructor throw returned the valid pointer








Example 2 :

Normally we

#include
#include
using namespace std;

void nothrowTesting()
{
int *p;

p = new(nothrow) int[20];

if( p == NULL)
{
printf("\n Memory allocation is failed...");
return;
}
else
{
printf("\n Memory Allocation is succeeded...");
}



if(p)
{
delete [] p;
p = NULL;
}
}


int main(int argc, char* argv[])
{
nothrowTesting();
return 0;
}


Example 3 :
-------------------------




#include
#include
using namespace std;
class nothrowClass
{
public:
nothrowClass() ;
~nothrowClass();


};

nothrowClass::nothrowClass()
{
printf("\n constructor..");
throw 100;
}

nothrowClass::~nothrowClass()
{
printf("\n destructor..");

}

void nothrowTestingClient()
{
nothrowClass* pClass;

try
{

pClass = new nothrowClass();

if(pClass == NULL)
{
printf("\n Invalid Pointer");

}
else
{

printf("\n valid Pointer");

if(pClass)
{
delete pClass;
pClass = NULL;
}


}
}
catch(...)
{
printf("\n Error in Allocation..");
}
}

int main(int argc, char* argv[])
{
nothrowTestingClient();
return 0;
}


output :
-----------
constructor
Error in Allocation (exception)
if the exception occurs the normal flow of program will be affected... So How can we handle this situation ?...

Example 4:
-------------------

#include

class Base
{
public:
Base()
{

}
~Base()
{

}

void DisplayBase()
{
printf("\n Base Display");
}


};

class Derived: public Base
{
public:
Derived()
{
}

~Derived()
{
}
void DisplayDerived()
{
printf("\n Derived Display");
}


};


int main(int argc, char* argv[])
{
Derived d;
Base* bp;

bp = &d; // we r typecasting the derived class to base class
bp->DisplayBase();

//bp->DisplayDerived() fn is an error we have to call like this...

((Derived*)bp)->DisplayDerived(); //This is the use of typecasting
return 0;
}


Example 5:
---------------------

#include

// .* and ->* are pointer to member operators

class PointerToMember
{
public:

int (PointerToMember::*fn)();

int (PointerToMember::*fn2)();

PointerToMember(int i)
{
val = i;
fn = double_val;
fn2 = double_val;

}


int val;
int double_val() { return val+val; }


int callPointer()
{
return (this->*fn)();
}





};

int main(int argc, char* argv[])
{


PointerToMember p(1); //Initialize the constructor of the class

printf("\n fn return value is : %d",p.callPointer());


return 0;
}

Sunday, June 03, 2007

Object conversion

#include "stdio.h"
class ObjectConversion
{
public:
ObjectConversion() { }
~ObjectConversion(){ }

operator int() { return 10; }
operator double(){ return 12.002; }

};

void ObjectConversionClient()
{
ObjectConversion obj;
int i ;
double d;

i = obj;
d = obj;

printf("\n value of i is %d",i);
printf("\n value of d is %lf",d);
}
int main(int argc, char* argv[])
{
ObjectConversionClient();
return 0;
}


The output for this program is :

value of i is 10
value of d is 12.00200

Cpp Exceptions

Exceptions :
1.

The following code will catch the exception:

try
{
throw 100;
}
catch(int i)
{
printf(“\n Exception :%d”, i );
}


Exception :
Exception Testing () fn didn’t handle the exception then it will throws the exeption to the called function.


void ExceptionTesting()
{
throw 100;
}

int main(int argc, char* argv[])
{
try
{
ExceptionTesting();
}
catch(int i)
{
printf("\n main() fn exception : %d",i);

}
return 0;
}

Catching class types:
We can also create our own exceptions.

//Catching class type exceptions
#include
#include

class MyException
{
public:


MyException() { }

~MyException(){ }


};

int main(int argc, char* argv[])
{
int i = 0;

try
{
if(i == 0)
{
throw MyException();
}
}
catch(MyException e)
{
printf("\n Base classException");
}

return 0;
}
Catching Derived class Exception:

We can catch the derived class using the base class .

//Catching class type exceptions
#include
#include
class MyException
{
public:
MyException() { }
~MyException(){ }
};

class Derived:public MyException
{
public:
Derived(){ }
~Derived(){ }
};
int main(int argc, char* argv[])
{
int i = 0;

try
{
if(i == 0)
{
throw Derived();
}
}
catch(MyException e)
{
printf("\n Base classException");
}
catch(Derived d)
{
printf("\n Derived class Excption");
}

return 0;
}


Even though we passed the derived class exception, the base class will catch the “Base class Exception”.

Warning C4286: 'class Derived' : is caught by base class ('class MyException')

Wednesday, May 30, 2007

What is the difference between 'delete' and 'delete[]'?

What is the difference between 'delete' and 'delete[]'?

Whenever you allocate memory with 'new[]', you have to free the memory using 'delete[]'. When you allocate memory with 'new', then use 'delete' without the brackets. You use 'new[]' to allocate an array of values (always starting at the index 0).

int *pi = new int; // allocates a single integer
int *pi_array = new int[10]; // allocates an array of 10 integers
delete pi;
pi = 0;
delete [] pi_array;
pi_array = 0;

'delete' frees the memory allocated to a single object,
while 'delete []' frees memory allocated to an array of objects, and
ensures the correct destructors are invoked


Sample program for testing the above concept:

We can use the static variable inside the non-static member function.


#include “string.h”
#include “conio.h”


class CMyClass
{
static int ObjectCount;
public:
CMyClass() ;
~CMyClass();
};

int CMyClass::ObjectCount = 0; //static member initialisation

CMyClass::CMyClass()
{
ObjectCount++;
printf("\n CMyClass constructor: Objects :%d",ObjectCount);
}

CMyClass::~CMyClass()
{
ObjectCount--;
printf("\n CMyClass destructor: Objects :%d",ObjectCount);

}


void DeletePtrTesting()
{
CMyClass* m_pClass;

m_pClass = new CMyClass[3];


if(m_pClass)
{
delete m_pClass;
}
}


void DeleteArrayTesting()
{
CMyClass* m_pClass;

m_pClass = new CMyClass[3];


if(m_pClass)
{
delete[] m_pClass;
}
}

int main(int argc, char* argv[])
{
//DeletePtrTesting();
DeleteArrayTesting();
getch();
return 0;
}


if we called the DeletePtrTesting() fn , it deletes the pointer alone

delete m_pClass;

Result :

CMyClass constructor: Objects :1
CMyClass constructor: Objects :2
CMyClass constructor: Objects :3
CMyClass destructor: Objects :2


Only one object is deleted from memory and 2 more objects are not deleted from memory.


But if we called the DeleteArrayTesting(), it deletes as follows

delete [] m_pClass;

and observe the output …

Result :

CMyClass constructor: Objects :1
CMyClass constructor: Objects :2
CMyClass constructor: Objects :3
CMyClass destructor: Objects :2
CMyClass destructor: Objects :1
CMyClass destructor: Objects :0


All the objects are deleted from memory. So whenever we create a pointer with new[], we have to delete the memory using delete[].

Usage:

Memory allocation Memory Deallocation
new delete
new[] delete[]