Thread: different way of initializing variable?

  1. #1
    Registered User
    Join Date
    Aug 2001
    Posts
    84

    different way of initializing variable?

    hi,

    i just read that you can initialize a variable

    int num = 10;

    like this

    int num(10)

    does any one ever do this ? are there any differences at all however subtle between the 2?

    Thanks.

  2. #2
    Registered User
    Join Date
    Sep 2001
    Posts
    20
    I do this as well.

    int num = 10; <-- creates the variable, initializes with the default value, then assigns 10 to it.

    int num(10); <-- creates the variable and initializes it with whatever's between the parentheses, using the constructor.

  3. #3
    Registered User
    Join Date
    Aug 2001
    Posts
    154

    Re: different way of initializing variable?

    Originally posted by The Gweech
    hi,

    i just read that you can initialize a variable

    int num = 10;

    like this

    int num(10)

    does any one ever do this ? are there any differences at all however subtle between the 2?

    Thanks.
    That's (parantheses) the standard way to initialize a programmer defined class object, at least as far as I've learned .
    E.g., you create a class called Employee that contains first & last names & id #. When you create an object of class Employee, you can initialize it it like this:
    Code:
    Employee peon("Joe", "Sixpack", 666);
    A class is like a built in type (int, double, char, etc). There are probably differences, but that's what I've learned so far.

  4. #4
    Registered User
    Join Date
    Sep 2001
    Posts
    2

    No Difference

    There is actually no real difference in the two different syntaxes, but the parenthetical syntax is required in the initialization lists for class constructors:


    class some_class
    {
    public:
    some_class() : varone(1), // Parentheses used here
    vartwo(2),
    varthree(3)
    {
    // Initialize...
    }
    private:
    int varone, vartwo, varthree;
    };

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. how to put a check on an extern variable set as flag
    By rebelsoul in forum C Programming
    Replies: 18
    Last Post: 05-25-2009, 03:13 AM
  2. sorting number
    By Leslie in forum C Programming
    Replies: 8
    Last Post: 05-20-2009, 04:23 AM
  3. Question about printing a variable???
    By Hoser83 in forum C++ Programming
    Replies: 2
    Last Post: 03-31-2006, 01:57 PM
  4. How accurate is the following...
    By emeyer in forum C Programming
    Replies: 22
    Last Post: 12-07-2005, 12:07 PM
  5. static class variable vs. global variable
    By nadamson6 in forum C++ Programming
    Replies: 18
    Last Post: 09-30-2005, 03:31 PM