Monday, May 24, 2010

C program help?

here is the prog


#include%26lt;iostream.h%26gt;


class star


{


private:


int inum3,inum4;


public:


int ivar=inum1;


void add(int inum1,int inum2)


{


inum3=inum1+inum2;


cout%26lt;%26lt;inum3%26lt;%26lt;endl;


}


void sub(int inum1,int inum2)


{


inum4=inum1-inum2;


cout%26lt;%26lt;inum4%26lt;%26lt;endl;


}


};


void main()


{


star var1;


var1.add(10,5);


var1.sub(10,5);


cout%26lt;%26lt;ivar%26lt;%26lt;endl;


}


can anyone explain the sequence in which program execution takes place.


i get error if i declare ivar in public.

C program help?
yes you get error because declarations are allowed only in private section and variables can b initialized only within constructor part.





then this program will do addition and subtraction operaion on inum1 and inum2 and print the answers and i have doubt ,you had printed that ivar1.








modified program:








#include%26lt;iostream.h%26gt;


class star


{


private:


int inum3,inum4int ivar;


public:


star() /* constructor part */


{


ivar=inum1;


}


void add(int inum1,int inum2)


{


inum3=inum1+inum2;


cout%26lt;%26lt;inum3%26lt;%26lt;endl;


}


void sub(int inum1,int inum2)


{


inum4=inum1-inum2;


cout%26lt;%26lt;inum4%26lt;%26lt;endl;


}


};


void main()


{


star var1;


var1.add(10,5);


var1.sub(10,5);


}
Reply:The problem is that ivar is being declared and assigned the value of inum1, but inum1's value is indeterminate. In fact, it's not even declared by the time the star class would have been constructed. Instead, declare ivar as equaling 0 when initialized. In fact, it's good programming practice to do this for all class level variables.
Reply:Execution in C and Java always starts with the main method. Try declaring ivar in the main method and maybe that will work. It's hard to help without a compiler right in front of me, but this is a starting point.


No comments:

Post a Comment