You are here:

C++/Classes and Member declarations !

Advertisement


Question
#include<iostream.h>
class star
   {
    private:
   int inum3,inum4;
    public:
   int ivar=inum1;
   void add(int inum1,int inum2)
     {
      inum3=inum1+inum2;
      cout<<inum3<<endl;
      }
   void sub(int inum1,int inum2)
     {
      inum4=inum1-inum2;
      cout<<inum4<<endl;
      }
     };
 void main()
    {
    star var1;
    var1.add(10,5);
    var1.sub(10,5);
    cout<<ivar<<endl;
    }
i want to know the sequence in which prog executes.step by step pl.i get error when i declare ivar in public

Answer
Dear Mr Selva!
   Before explaining the sequence let me explain the basic concepts in classes and member declaration that's  because i found some bugs related to that !
>> int ivar=inum1;
 Consider this statement , this is of course wrong in two way's
1. You cannot initialize a member just like we do with ordinary variable , ie the class member should be initialized either inside the member function or by using constructor .
Hope you have to change the statement just like this
>> int ivar , inum1; will be the correct form .


Then consider this statement :
>> cout<<ivar<<endl;

You cannot access/use the class member ( ivar ) outside the class just what we do with normal variables  , only provision given to access the class member is using the object of that class , so in order  to print the value of ivar you have to use the following statement  

cout<<var1.ivar; if you alter these statements sure you won't get error !

Execution sequence !

1.program starts with main()
2.object declaration ( star var1; )
   once after declaring the object , it will try to execute the constructors , if present , but here in this program you didnt use any constructor .

3. Member ( public) functions are invoked using the class objects
4. And the final statement is a well known error , just no we discussed it

If you have any queries , please do follow up me !

Thanks and Regard!

Prince M. Premnath.  

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Prince M. Premnath

Expertise

Years of research in C/C++ Will bring you all facts regarding , OOPS , SVGA , MOUSE , BIOS , IVT , Feel free to query me :-)

Experience

More than 5 years

Education/Credentials
MCA

©2016 About.com. All rights reserved.