Thread: An Interesting Code Sample

  1. #1
    Registered User
    Join Date
    Apr 2007
    Posts
    284

    An Interesting Code Sample

    Code:
    class Base{
    pulbic:
    	void foo() const{
    		cout<<"Base Class: void"<<endl;
    	}
    
    	int foo() {
    		cout<<"Base Class: int"<<endl;
    		return 1;
    	}
    };
    
    int main(){
    
    Base test;
    test.foo();
     return 1;
    }
    It can pass compiling. But how does the compile know which function I want to call?

  2. #2
    Registered User
    Join Date
    Apr 2007
    Posts
    284
    In other words, how can I call the function
    void foo() const ?

  3. #3
    Registered User
    Join Date
    Aug 2005
    Location
    Austria
    Posts
    1,990
    Call foo() with a const reference.

    Code:
    #include <iostream>
    
    using namespace std;
    
    class Base{
    public:
    	void foo() const{
    		cout<<"Base Class: void"<<endl;
    	}
    	int foo() {
    		cout<<"Base Class: int"<<endl;
    		return 1;
    	}	
    };
    int main(){
        Base test;
        test.foo();
        
        const Base & b = test;
        b.foo();    
        return 1;
    }
    my output
    Code:
    Base Class: int
    Base Class: void
    Kurt

  4. #4
    The larch
    Join Date
    May 2006
    Posts
    3,573
    To avoid confusion, you just shouldn't try to overload functions based on return type. Overloads based on const-ness are normal though (the [] operator usually).
    I might be wrong.

    Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.
    Quoted more than 1000 times (I hope).

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Any sample code availble?
    By krishnampkkm in forum Windows Programming
    Replies: 1
    Last Post: 06-19-2009, 04:41 AM
  2. How to get the sample code?
    By krishnampkkm in forum C++ Programming
    Replies: 2
    Last Post: 06-19-2009, 04:41 AM
  3. Sample code please help!!!
    By aewing30 in forum C Programming
    Replies: 6
    Last Post: 05-29-2008, 10:51 AM
  4. True ASM vs. Fake ASM ????
    By DavidP in forum A Brief History of Cprogramming.com
    Replies: 7
    Last Post: 04-02-2003, 04:28 AM
  5. Interface Question
    By smog890 in forum C Programming
    Replies: 11
    Last Post: 06-03-2002, 05:06 PM