70 likes | 189 Views
#include <iostream.h> #include <string.h> class Student { public: Student( char *pName) { cout<<“Constructing student “<<pName<<endl; strncpy( name, pName, sizeof(name) ); name[sizeof(name)-1]=‘’; semesterHours=0; gpa=0.0; }
E N D
#include <iostream.h> #include <string.h> class Student { public: Student( char *pName) { cout<<“Constructing student “<<pName<<endl; strncpy( name, pName, sizeof(name) ); name[sizeof(name)-1]=‘\0’; semesterHours=0; gpa=0.0; } ~Student() { cout<<“Destructing “<<name<<endl; } protected: char name[40]; int semesterHours; float gpa; }; void main() { Student s(“Danny”); }
Overloading of constructors is allowed —In the same class, you may have several constructors with different arguments Overloading of destructors is of course not allowed (why?) #include <iostream.h> #include <string.h> class Student { public: Student() { semesterHours=0; gpa=0.0; name[0]=‘\0’; Student( char *pName ) { strncpy( name, pName, sizeof(name) ); name[sizeof(name)-1]=‘\0’; semesterHours=0; gpa=0.0; }
Student( char *pName, int xfrHours, float xfrGPA ) { strncpy( name, pName, sizeof(name) ); name[sizeof(name)-1]=‘\0’; semesterHours=xfrHours; gpa=xfrGPA; } ~Student() { cout<<“Destructing students\n”; } protected: char name[40]; int semesterHours; float gpa; }; int main() { Student noName; Student freshman( “Smell E. Fish” ); Student xfer( “Upp R. Classman”, 80, 2.5 ); return 0; }
#include <iostream.h> #include <string.h> class Student { public: Student( char *pName=“no name”, int xfrHours=0, float xfrGPA=0.0 ) { strncpy( name, pName, sizeof(name) ); name[sizeof(name)-1]=‘\0’; semesterHours=xfrHours; gpa=xfrGPA; } ~Student() { cout<<“Destructing students\n”; } protected: char name[40]; int semesterHours; float gpa; }; void main() { Student noName; Student freshman( “Smell E. Fish” ); Student xfer( “Upp R. Classman”, 80, 2.5 ); }
#include <iostream.h> #include <string.h> class StudentId { public: StudentId( int id=0 ) { value=id; cout<<“Assigning student id “<<value<<endl; } protected: int value; }; class Student { public: Student( char *pName=“no name”, int ssId=0 ) { cout<<“Constructing student “<<pName<<endl; strncpy( name, pName, sizeof(name) ); name[sizeof(name)-1]=‘\0’; StudentId id(ssId); } protected: char name[40]; StudentId id; };
int main() { Student s(“Randy”, 1234); cout<<“This message from main\n”; return 0; } Output: Assigning student id 0 Constructing student Randy Assigning student id 1234 Destructing id 1234 This message from main Destructing id 0
class Student { public: Student( char *pName=“no name”, int ssId=0 ) : id(ssId) { cout<<“Constructing student “<<pName<<endl; strncpy( name, pName, sizeof(name) ); name[sizeof(name)-1]=‘\0’; } protected: char name[40]; StudentId id; } Output: Assigning student id 1234 Constructing student Randy This message from main Destructing id 1234