C++/question

Advertisement


Question
Can we use the same function name for a member function of a class and an outside function in the same program file?can u sugest an exmple.


Answer
Yes and I am surprised you cannot think of an example as you asked the question you must have some such situation in mind, and of course could have answered it yourself with some quick test code:

   class C   
   {
   public:
       void clear();
   };
   
   void clear();
   
   namespace N
   {
       void clear();
   }

I show only the function declarations (prototypes).

Class definitions define namespaces and divide up the naming space hence C::clear() is different from ::clear (the two :: here indicate the global namespace), which are both different from N::clear().

Function names can also be the same in the same namespace (global, C++ namesapce or class) if they have different numbers or types of parameters - this is called function overloading.

Here are some  real world examples taken from the C++ standard library, again with just function declarations shown:

1/ from <cmath>:

   namespace std
   {

   // ...

       float       tan(float);
       double      tan(double);
       long double tan(long double);

   // ...

   }
   
2/ from <string>:

   namespace std
   {

   // ...

       template
       < class charT
       , class traits = char_traits<charT>
       , class Allocator = allocator<charT>
       >
       class basic_string
       {

       // ...

       public:

       // ...

         size_type find( const basic_string& str, size_type pos = 0) const;
         size_type find( const charT* s, size_type pos, size_type n) const;
         size_type find( const charT* s, size_type pos = 0) const;
         size_type find( charT c, size_type pos = 0) const;

       // ...

       };

   // ...

   }

3/ From <istream> and <string> showing both your original query and overloading:

   // non-member std::getline functions for use with std::string types and std::istream types
   // declared in <string>
   namespace std
   {

   // ...

       template
       < class charT
       , class traits
       , class Allocator
       >
       basic_istream<charT,traits>&
       getline( basic_istream<charT,traits>& is, basic_string<charT,traits,Allocator>& str, charT delim );

       template
       < class charT
       , class traits
       , class Allocator
       >
       basic_istream<charT,traits>&
       getline( basic_istream<charT,traits>& is, basic_string<charT,traits,Allocator>& str )

   // ...

   }

   // member std::basic_istream<>::getline functions for use with C-strings types and std::istreams
   // types declared in <istream>
   namespace std
   {

   // ...

       template
       < class charT
       , class traits = char_traits<charT>
       >
       class basic_istream : virtual public basic_ios<charT,traits>
       {
       public:

       // ...

         basic_istream<charT,traits>& getline( char_type* s, streamsize n );
         basic_istream<charT,traits>& getline( char_type* s, streamsize n, char_type delim );

       // ...

       };

   // ...

   }

The above come from the C++ standards document, with some reformatting to attempt to make things a little easier to read (not sure how much better though). As you will notice the many of the underlying types and functions are in fact templates to create actual classes and functions. The primary reason for this in the case of stings and streams is to support both narrow (char) and wide (wchar_t) character types by default and allow custom character types to be possible. The other reason, like a lot of the C++ standard library types, is to allow the use of custom allocators to handle memory allocation and deallocation.

The final re-use of function names is in class hierarchies to support polymorphism, and allows a member function in a derived class, having the same name and number and types of parameters and compatible return type to override the behaviour of the base implementation. Such functions in C++ are called virtual functions and are declared in at least the initial base class with the keyword 'virtual':

   class Widget
   {

   // ...

   public:
       virtual result_type draw(DrawContext);  // probably does very little
       
       virtual ~Widget();  // *must* declare virtual destructor if using polymorphism

   // ...

   };

   class Textbox : public Widget
   {

   // ...

   public:
       result_type draw(DrawContext); // still virtual; draws text box
       
       ~Textbox(); // still virtual;

   // ...

   };

I am not going to explain all the ifs and buts and whys and wherefores of polymorphism and C++ function overriding at it is quite involved and not directly related to your question. If you are interested  please refer to the C++ FAQ at http://www.parashift.com/c++-faq-lite/, starting with section 20 (and 19 if you have not come across inheritance at all yet).

Hope this answers your question and has provided enough examples for you to be getting on with.  

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Ralph McArdell

Expertise

I am a software developer with more than 15 years C++ experience and over 25 years experience developing a wide variety of applications for Windows NT/2000/XP, UNIX, Linux and other platforms. I can help with basic to advanced C++, C (although I do not write just-C much if at all these days so maybe ask in the C section about purely C matters), software development and many platform specific and system development problems.

Experience

My career started in the mid 1980s working as a batch process operator for the now defunct Inner London Education Authority, working on Prime mini computers. I then moved into the role of Programmer / Analyst, also on the Primes, then into technical support and finally into the micro computing section, using a variety of 16 and 8 bit machines. Following the demise of the ILEA I worked for a small company, now gone, called Hodos. I worked on a part task train simulator using C and the Intel DVI (Digital Video Interactive) - the hardware based predecessor to Indeo. Other projects included a CGI based train simulator (different goals to the first), and various other projects in C and Visual Basic (er, version 1 that is). When Hodos went into receivership I went freelance and finally managed to start working in C++. I initially had contracts working on train simulators (surprise) and multimedia - I worked on many of the Dorling Kindersley CD-ROM titles and wrote the screensaver games for the Wallace and Gromit Cracking Animator CD. My more recent contracts have been more traditionally IT based, working predominately in C++ on MS Windows NT, 2000. XP, Linux and UN*X. These projects have had wide ranging additional skill sets including system analysis and design, databases and SQL in various guises, C#, client server and remoting, cross porting applications between platforms and various client development processes. I have an interest in the development of the C++ core language and libraries and try to keep up with at least some of the papers on the ISO C++ Standard Committee site at http://www.open-std.org/jtc1/sc22/wg21/.

Education/Credentials

©2016 About.com. All rights reserved.