Sunday 8 September 2013

Forward referencing

Tags

What is forward referencing and when should it be used?

Ans: Consider the following program:  


                       class test                        {
                       public :
                       friend void fun ( sample, test ) ;                          } ;
                       class sample                        {
                       public :
                       friend void fun ( sample, test ) ;
                       } ;
                       void fun ( sample s, test t )                        {
                       // code                          }
                       void main( )                        {
                       sample s ;                        test t ;                        fun ( s, t ) ;
                       } 


This program would not compile. It gives an error that sample is undeclared identifier in the statement friend void fun ( sample, test ) ; of the class test. This is so because the class sample is defined below the class test and we are using it before its definition. To overcome this error we need to give forward reference of  the class sample before the definition of class test. The following statement is the forward reference of  class sample. Forward referencing is generally required when we make a class or a function as a friend.


EmoticonEmoticon