Tuesday, July 28, 2009

C++ classes & constructors?

1. is it mandatory to use a constructor in a class?


2. write a class Student having two data members (int roll_no and char name[25]) Write functions to get the i/p %26amp; to display the data of the objects of this class. Write a function which will count the no. of objects created


Does this code satisfy the question?


class student


{char name[25];


int roll_no;


static int count;


public:


student()


{name[25] = 0;


roll_no = 0;


count++}


void getdata()


{cin %26gt;%26gt; name %26gt;%26gt; roll_no;


}


void showdata()


{cout %26lt;%26lt; name %26lt;%26lt; roll_no;


}


void showcount()


{cout %26lt;%26lt; count;


}


int student :: count;


};


void main()


{student s1, s2;


s1.getdata();


s2.getdata();


s1.showdata();


s2.showdata();


s1.showcount();


s2.showcount();

C++ classes %26amp; constructors?
1) It's a good start.





2) How will you learn if you don't do the work. You're missing a closing } in int main, plus... Does it compile?
Reply:1) no


2) Do your own homework
Reply:As everyone has said, no you don't need a CTOR. If you don't create one, the compiler creates a default one for you.





As to your program. Here are a few comments to get you STARTED. This is not a complete list of all your problems.





1. You need to comment it. Your instructor probably requires you to, and not commenting will not pass muster (code reviews) with the "real world."


2. I don't know what you mean by "get the i/p." I/P is an overloaded term that has different meanings based on the environment. I assume (from the code) that it just means to input the data. If that is the case, calling getdata() does not put the values into the member variables.


3. In main(), you need to create s1 and s2 by using the new operator.
Reply:A class constructor is a class member function that assigns an initial value to each of the class data members. If you do not write your own class constructor, the compiler will create a default version. So a class constructor gets used even if you do not write one yourself.

wedding floral centerpieces

No comments:

Post a Comment