Thursday, August 12, 2010

Friend function in C++ Explained

A friend function is a function that can access the private members of a class as though it were a member of that class. In all other regards, the friend function is just like a normal function. A friend function may or may not be a member of another class. To declare a friend function, simply use the friend keyword in front of the prototype of the function you wish to be a friend of the class. It does not matter whether you declare the friend function in the private or public section of the class.

Here is a small snippet for friend function..try it.

class base
{
private:
        int s;
public:
     base()
       {
       cout<<"s value is"<
       }
friend nonmember(base &a);
};


nonmember(base &a)
{
cout<<"s value from class base is"<
}


void main()
{
base p;
nonmember(p);
}





 
read more...

C program without Main

Hai friends here is a c program without main function.

#include
#include
#define START main(){
#define END }

START

clrscr();
printf("Hai how r u!");
getch();
return 0;

END
read more...

Overloading assignment operator = in C++

 Complete program for assignment operator overloading....


#include "iostream.h"
#include "malloc.h"
#include
class Myclass
{
public:
int app,bat;

        void show();
    void* operator =(Myclass);
         Myclass(int a,int b)
        {
    app=a;
    bat=b;

    }

};
void* Myclass::operator =(Myclass ob)
{
app=ob.app;
bat=ob.bat;
return this;
}
void Myclass::show()
{
cout<<"after assignment operator overloading is:"<<<"\t\t"<
}
void main()
{
Myclass ob(0,0);
Myclass ob2(23,45);
ob=ob2;
ob.show();
getch();
}
read more...

Overloading New and Delete operators in C++

Here is a complete C++ program for new and delete operator overloading  ..

#include "iostream.h"
#include "malloc.h"
#include
class Myclass
{
public:

    void* operator new(size_t);
    void operator delete(void* p);
};
void* Myclass::operator new(size_t size)
{
    void* storage = malloc(size);
    if(NULL == storage) {
        cout<<"allocation fail : no free memory";

    }
    cout<<"size is:"<<<",storage location is:"<
    return storage;

}

void Myclass::operator delete(void* p)
{

free(p);
cout<<"allocated memory removed from location:"<}
void main()
{
clrscr();
Myclass *x = new Myclass;
cout<<"\n\n\n\n\n\n\n\n";
delete x;
getch();
}
read more...