C++ Archive

Note: Just a place to share some interesting code snippets. Please don’t copy the programs as-is into a C++ editor and expect them to work, because I’ve introduced line breaks in some places to fit it into the window of this page, and you’re bound to get some errors because of the breaks. Otherwise, things should work fine!

  • Pointer Funda(c) SGP 2002-2006. Lots of pointers. The comments within the program explain their uses. Enjoy!!! 🙂 */
    #include <iostream>
    int val;
    int newArr[2];
    int (*ptrArr)[2];                                                   
    //Function returning int* and accepting int* as argument
    int* fn_retptr(int* temp)
    	return &val;
    //Function returning pointer to array of two integers, and accepting int*
    int (*fn_retarr(int* temp))[2]
    	return (&newArr);
    //Function accepting pointer to array of two integers and returing int*
    int* fn_retptrarr(int (*ptr_arr)[2])
    	return &val;
    //Function accepting array of pointers to int, and returning int*
    int* fn_arrptr(int* arrPtr[5])
    	return &val;
    int* fn_trial(int* temp)
    	return &val;
    //Function returning pointer to function and accepting pointer to function
    int* (*fn_ptrfn(int* (*ptrfunc)(int*)))(int*)
    	int tempval=34;
    	cout<<"10) Output from function returning pointer to function
    	and accepting pointer to function as argument: Value from function
    	received as input = "<<*(ptrfunc(&tempval))<<endl;
    	return &(fn_trial);
    	int a=10;                                                   
    	//1) Pointer to int
    	int* pInt=&a;
    	cout<<"1) pInt:pointer to int: points to a = "<<*pInt<<endl;                                  
    	//2) Array of pointers to int
    	int arr[5];
    	int* arrPtrInt[5];
    	cout<<"2) arrPtrInt:array of pointers to int"<<endl;
    	for(int i=0;i<5;i++)
    		cout<<"Value of pointer to int "<<i+1<<" = "<<*(arrPtrInt[i])<<endl;
    	//3) Ptr to array of int
    	int (*ptrArrInt)[5]=&arr;
    	cout<<"3) ptrArrInt:ptr to array of int points to "<<(*ptrArrInt)[0]<<endl;
    	//4) Fn that returns ptr to int, and takes
                  ptr to int argument : See above defn of fn_retptr
    	int b=2;
    	cout<<"4) Fn_retptr accepting int*
             and returning int* = "<<*fn_retptr(&b)<<endl;           
    	//5. ptr to function that returns pointer to int
    	int* (*ptrFunc)(int*)=&fn_retptr;
    	cout<<"5) Invoking fn_retptr through pointer
             that points to it = "<<*ptrFunc(&b)<<endl;                                                   
    	//6. Fn that returns ptr to array of int, accepts int*: See above fn_retarr
    	cout<<"6) Invoking fn_retarr that returns pointer to
             arr of int and accepts int* = "<< *((fn_retarr(&b))[0])<<endl;                                
    	//7. Fn that accepts ptr to array as argument,
                 returns ptr to int: See above fn_retptrarr
    	int newIntArr[3]={10,20,30};
              cout<<"7) Invoking fn_retptrarr accepting pointer to array of int
    	and returns pointer to int = "<<*(fn_retptrarr((int(*)[2])&newIntArr))<<endl;
    	//8. Fn that takes array of pointers as argument: See above fn_arrptr
    	cout<<"8) Invoking fn_arrptr accepting array of pointers
             and returning pointer to int = "<<*(fn_arrptr(arrPtrInt))<<endl;
              //9. Array of pointers to functions that take int* and return int*
    	int* (*(p_func[2]))(int*);
    	cout<<"9) Value of 1st element in array of pointers
    	to functions p_func = "<<*((*p_func[0])(&b))<<endl;                 
    	//10. Pointer to function returning pointer to function
                  and accepting pointer to function
    	int* (*(*p_funcfunc)(int* (*)(int*)))(int*);
    	int* (*p_func2)(int*);
    	int x=100;
              cout<<"11) Calling Ptr to function returning pointer
    	to function and accepting pointer to function : output from the
    	returned pointer to function = "<<*(p_func2(&x))<<endl;
              int** ptr_ptr;
    	cout<<"12) Pointer to Pointer: Back to first value = "<<**ptr_ptr<<endl;

  • Pointer to Member
    /* (c) SGP 2002-2006. This example demonstrates the usage of ptr
    to function and ptr to member functions ptr_add is a pointer to
    the global function add, and can be invoked as it is, but ptr_mem_add
    is a pointer to the non-static member function of Sum, and has to be
    invoked with the object of Sum. If the member function is a static
    function, then the syntax of the pointer to the static member
    function will be same as pointer to simple function.*/                                            
    #include <iostream>                                            
    //A class which has a member function add
    class Sum
    	int c;
    	int& add(int& a,int& b)
    		return c;
    //A Global function add
    int add(int& a,int& b)
    	return a+b;
    //A Function which takes function pointers as arguments
    void displayValue(int (*ptr2func) (int&, int&), int&
    (Sum::*ptr2memfunc) (int&, int&), int& a, int& b)
    	Sum oSum;
    	cout<<"Sum using pointer to function "<<ptr2func(a,b)<<endl;
    	cout<<"Sum using pointer to member function "<<(oSum.*ptr2memfunc)(a,b)<<endl;
    	int a,b;
    	//Creating pointer to function
    	int (*ptr_add) (int&,int&) = &add;
             //Comparison of pointer's value with address of global function
    		cout<<"ptr_add points to global function add"<<endl;
    		cout<<"Error in pointer assignment of ptr_add"<<endl;
             //Creating pointer to member function
    	int& (Sum::*ptr_mem_add) (int&, int&)= &(Sum::add);
             //Comparing function pointer to member function address
    		cout<<"ptr_mem_add points to member function of Sum"<<endl;
    		cout<<"Error in pointer assignment of ptr_mem_add"<<endl;
             //Input of two numbers
    /*       This demonstrates calling the functions using the pointers within the code
               //Calling global function using Function pointer
    	cout<<"Sum from pointer to function ";
               //Calling member function using Function pointer
    	cout<<"Sum from the pointer to member function ";
               //Here we are passing the pointers to a function and there they are called.
    	displayValue(ptr_add, ptr_mem_add, a, b);

  • Pointers and Constants
    #include <iostream>                           
    	int nVal = 30;
    	int* pVal;
    	pVal=&nVal;	//Pointer to int
    	cout<<"Pointer pVal value = "<<*pVal<<endl;
    	cout<<"Variable Value after changing through pointer = "<<nVal<<endl;
    	const int ncVal=10;
    	const int* pcVal;
    	pcVal = &ncVal;
    	cout<<"Pointer to const val pcVal value = "<<*pcVal<<endl;
             //The following is an error: Assigning value to read-only location
    	//*pcVal = 100;
    	//The following is an error: Assigning value to read-only variable
    	//ncVal = 100;
              //The following is an error: Cannot assign pointer to
    	//int, to point to const int value
    	//int* pcVal2 = &ncVal;	
    	The following is allowed by some compilers:
    	Assigning pointer to const int to int
    	Here pcVal is ptr to const int, but not a const pointer
    	so the location it points to can be changed
     	pcVal = &nVal;
             cout<<"Variable value accessing using ptr to const int = "<<*pcVal<<endl;
    	int* const cpVal = &nVal;
    	int nVal2 = 200;
    	cout<<"Variable value accessing using
    	const pointer to int = "<<*cpVal<<endl;
             //The following is an error: Re-assigning const
    	//pointer is not allowed
    	//cpVal = &nVal2; 
                      //The following is an error: Cannot assign const
    	//pointer to int to point to const int
    	//int* const cpVal2 = &ncVal;
    	Assigning const pointer to const int to a const int is permitted.
    	Here value of const int cannot be changed and the pointer cannot
    	be used to point to any other const int either
    	const int* const cpcVal = &ncVal;
    	cout<<"Value of const int accessed using const pointer
    	to const int = "<<*cpcVal<<endl;

  • Array of Pointers to Members
    /* The following program creates an array of pointers to
    member functions within a class Week. Based on the input,
    these member functions are called. There is also a member
    function inside the class, which returns the pointer to the
    corresponding function as the input. The same output can be
    got by using this member function to get the pointer to the
    individual functions and call them. The whole syntax is shown
    originally, and also using MACROS, to improve readability.
    In this case MACROS are of use, but typically usage of MACROS
    is to be avoided. (c) SGP 2006*/                
    #include <iostream>  
    class Week;                
    typedef void (Week::*ptr2Function) ();                
    #define CALL_MEMBER_FN(object,ptrToMember) ((object).*(ptrToMember))                
    #define CALL_FN_RET_MEMBER(object, funcName) (object.funcName)                
    class Week
    	void printDay0()
    	void printDay1()
    	void printDay2()
    	void printDay3()
    	void printDay4()
    	ptr2Function getDay(int& a)
    			case 1: return &Week::printDay0;
    			case 2: return &Week::printDay1;
    			case 3: return &Week::printDay2;
    			case 4: return &Week::printDay3;
    			case 5: return &Week::printDay4;
    	ptr2Function funcArr[5];
     	Week oWeek;
    	int day;
    	cout<<"Enter the day number [1-5] ";
    	cout<<"Day of the week from array of function pointers ";                
    	// Normally the call will be done as this
    	// (oWeek.*funcArr[day-1])();                
    	//Using a MACRO we can call now like this: This improves readability
    	CALL_MEMBER_FN(oWeek, funcArr[day-1])();
     	cout<<"Day of the week from function returning ptr to function ";
    	// Again, the call can be done without using the MACRO as the following
    	// (oWeek.*oWeek.getDay(day))();
     	//Using the MACRO, we will call the function as
    	CALL_FN_RET_MEMBER(oWeek, *oWeek.getDay(day) )();

  • Casting Pointers to Members
    /* Can you cast pointers to members? Well, yes, to pointers to members
     * of same classes, or those which are unambiguously
     * derived from the class. This example gives examples
     * to this. This will not work if a class is virtually derived from another*/
    #include  <iostream>
    using namespace std;       
    class A
    	int a;
    	int func1()
    		cout<<"function 1 called"<<endl;
    		return 1;
    	virtual float func2()
    		cout<<"function 2 called"<<endl;
    		return 1.0;
    class B : /*virtual*/ public A	//Virtual here will make casting wrong 
    	float func2()
    		cout<<"B function 2 called"<<endl;
    		return 2.0;
            int (A::*ptrA) () = &A::func1;
            A objA;
    float (A::*ptrB)() = (float (A::*)())ptrA ;
    int (A::*ptrC)() = ptrA;
    float (A::*ptrD)() = &(A::func2);
    float (B::*ptrBA)() = &B::func2;
            B objB;
            //This would work without casting
            //ptrBA = ptrD;
    //ptrD = (float (A::*)())ptrBA;	//C Style cast will always work
            ptrD = static_cast<float (A::*)()>(ptrBA);       

7 thoughts on “C++ Archive

  1. Pramod: Thanks for dropping by! Well, the original idea for the page came because I do have such a collection of cool code :).

    Unfortunately, haven’t been able to dump all the code yet, because of the bother of formatting it all into the page… but now I think I shouldn’t neglect this anymore… so hope to post more interesting programs, soon.

  2. Hi Shika,

    Your website have helped me a lot got to know about C++ & song lyrics.

    Good stuff..
    Keep smiling

  3. Required another song lyrics of “Aakasam thakela vadagalai ee nela andinche ahvanam premante…..” from Nuvvostanante Nenoddantana. plz……….

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s