variable names.

Discussion in 'C++' started by JustSomeGuy, Nov 12, 2003.

  1. JustSomeGuy

    JustSomeGuy Guest

    I just spent a few hours trying to find a bug in a friends code.
    I finally found it, but I'm shocked to see what is wrong.

    A private variable was defined in the class specification.
    The constructor also had a variable of the same name defined.

    We wondered why later on in the program things crashed. Well
    its obvious now, but there were absolutly no complier warnings
    about this variable. C++ doesn't seem to mind this and accepts it
    as normal. I think it shouldn't..

    Also when you have a constructor and the parameters to the constructor
    just set member variables, how does one go about declaring the method
    variables... We simple put underscores in the names of the variables and
    kept the rest of the variable names the same. Seems like a lot of work.
    Isn't there an easier way?
    JustSomeGuy, Nov 12, 2003
    #1
    1. Advertising

  2. JustSomeGuy escribió:

    > We wondered why later on in the program things crashed. Well
    > its obvious now, but there were absolutly no complier warnings
    > about this variable. C++ doesn't seem to mind this and accepts it
    > as normal. I think it shouldn't..


    Then don't use C++, use Ruby, for example ;)

    > Also when you have a constructor and the parameters to the constructor
    > just set member variables, how does one go about declaring the method
    > variables... We simple put underscores in the names of the variables and
    > kept the rest of the variable names the same. Seems like a lot of work.
    > Isn't there an easier way?


    You can use an initialsing list instead of assignments. That way the
    parameter of the constructor and the member variable can use the same
    name. But some people find this confusing and don't recommend it (the
    reuse of the name, not the initialising list).

    Here is an example:

    class Point {
    int x, y;
    public:
    Point (int x, int y) : x (x), y (y)
    { }
    };

    Regards.
    =?iso-8859-1?Q?Juli=E1n?= Albo, Nov 12, 2003
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Paddy McCarthy
    Replies:
    3
    Views:
    689
    Anthony J Bybell
    Sep 24, 2004
  2. Bob
    Replies:
    1
    Views:
    369
    Lucas Tam
    Jul 30, 2004
  3. wanwan
    Replies:
    3
    Views:
    413
    Alex Martelli
    Oct 14, 2005
  4. News123
    Replies:
    2
    Views:
    443
    John Machin
    Nov 26, 2008
  5. Peter Buckley
    Replies:
    5
    Views:
    191
    matt neuburg
    Feb 27, 2009
Loading...

Share This Page