Thread: wts diff b/w int i=100 , i=100 in constructor?

  1. #1
    kotin
    Join Date
    Oct 2009
    Posts
    132

    wts diff b/w int i=100 , i=100 in constructor?

    While executing below programs i getting different results

    Code:
    #include<iostream>
    using namespace std;
    class c
    {
    public :
    int i;
    c();
    };
    
    c::c()
    {
    int i=20;
    }
    int main()
    {
    c c1;
    cout<<c1.i<<"\n";
    return 0;
    }


    putput:1200034523


    Code:
    #include<iostream>
    using namespace std;
    class c
    {
    public :
    int i;
    c();
    };
    
    c::c()
    {
    i=20;
    }
    int main()
    {
    c c1;
    cout<<c1.i<<"\n";
    return 0;
    }

    output : 20



    anybody let me know the why if i place int in constructor it reflecting on result?


    i look for your further replys

  2. #2
    Registered User jdragyn's Avatar
    Join Date
    Sep 2009
    Posts
    96
    Code:
    c::c()
    {
    int i=20;
    }
    declares a local variable named i that only exists within the c() function. When c() ends, that i that you declared goes away. This means the class version of i is never touched, so it contains whatever garbage value that memory location had.

    Your second version without the int keyword in the constructor specifically sets the class version of i to 20.

  3. #3
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,318
    There's always the ideal C++ way to do it:
    Code:
    c::c() : i(20) {}
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. memory leak
    By aruna1 in forum C++ Programming
    Replies: 3
    Last Post: 08-17-2008, 10:28 PM
  2. Replies: 26
    Last Post: 11-30-2007, 03:51 AM
  3. getting a headache
    By sreetvert83 in forum C++ Programming
    Replies: 41
    Last Post: 09-30-2005, 05:20 AM
  4. Binary Search Trees Part III
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 16
    Last Post: 10-02-2004, 03:00 PM
  5. A Simple (?) Problem
    By Unregistered in forum C++ Programming
    Replies: 8
    Last Post: 10-12-2001, 04:28 AM