An Interesting Code Sample

This is a discussion on An Interesting Code Sample within the C++ Programming forums, part of the General Programming Boards category; Code: class Base{ pulbic: void foo() const{ cout<<"Base Class: void"<<endl; } int foo() { cout<<"Base Class: int"<<endl; return 1; } ...

  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
    ZuK
    ZuK is offline
    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, 05:41 AM
  2. How to get the sample code?
    By krishnampkkm in forum C++ Programming
    Replies: 2
    Last Post: 06-19-2009, 05:41 AM
  3. Sample code please help!!!
    By aewing30 in forum C Programming
    Replies: 6
    Last Post: 05-29-2008, 11: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, 06:06 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21