overloading question

This is a discussion on overloading question within the C++ Programming forums, part of the General Programming Boards category; Maybe it's not overloading... I don't know what it is. Basically: Code: int main() { int random; if (random > ...

  1. #1
    Just because ygfperson's Avatar
    Join Date
    Jan 2002
    Posts
    2,493

    overloading question

    Maybe it's not overloading... I don't know what it is.

    Basically:
    Code:
    int main() {
      int random;
      if (random > 3)
        int value;
      if (random <= 3)
        float value;
    
      add_factor(value);
    
    
    
    
    
    
    }
    void add_factor(int temp) {
    
    }
    void add_factor(float temp) {
    
    
    }
    Is this code illegal? Under what circumstances could value be used without error? (Pretend that these variables have values of some importance in them, and that add_factor(int) is different than add_factor(float).

  2. #2
    Registered User Codeplug's Avatar
    Join Date
    Mar 2003
    Posts
    4,607
    Its not legal. You are declaring "value" twice in their own statement blocks and don't have scope within main(). For example, the following is equivalent:
    Code:
    int main() 
    {
       int random;
       if (random > 3)
       {
          int value; //can't access value outside of {}
       }
       if (random <= 3)
       {
          float value;
       }
    
      add_factor(value); //value not defined in this scope
    
      return 0; //added for correctness
    }
    Your function declarations for add_factor() are ok. The type of the parameter will determine which function is called.

    You can accomplish what [it looks like] you were thinking like this:
    Code:
       if (random > 3)
          add_factor(<something of int type>);
       if (random <= 3)
          add_factor(<something of float type>);
    You can use templates and template specialization to do something similiar.

    gg

  3. #3
    Just because ygfperson's Avatar
    Join Date
    Jan 2002
    Posts
    2,493
    I see. Thanks.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Operator overloading question
    By 39ster in forum C++ Programming
    Replies: 3
    Last Post: 07-07-2007, 12:26 PM
  2. constructor overloading question
    By rozner in forum C++ Programming
    Replies: 6
    Last Post: 10-06-2006, 09:54 PM
  3. opengl DC question
    By SAMSAM in forum Game Programming
    Replies: 6
    Last Post: 02-26-2003, 08:22 PM
  4. Operator Overloading newbie question
    By Panopticon in forum C++ Programming
    Replies: 3
    Last Post: 01-03-2003, 06:14 PM
  5. Replies: 3
    Last Post: 01-22-2002, 11:25 AM

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