80 likes | 185 Views
Programming Paradigms. Lecturer Hamza Azeem. Lecture 9. Constructors Objects as Function Arguments. Constructors. It is a member function which initializes a class A constructor has: The same name as the class itself No return type. Classes. class KIETStudent { private: int age;
E N D
Programming Paradigms LecturerHamza Azeem
Lecture 9 ConstructorsObjects as Function Arguments
Constructors • It is a member function which initializes a class • A constructor has: • The same name as the class itself • No return type
Classes class KIETStudent { private: int age; char *name; double cgpa; char *intake; public: KIETStudent() { age = 0 ; name = “ “ ; cgpa = 0.0 ; intake = “ “ ; } intget_age(); };
Constructors • Constructors are used for initialization of variables • In previous example the variables were intialized • The preferred way for intializing variables is using Initializer List
Constructor using Initializer List class KIETStudent { private: int age; char *name; double cgpa; char *intake; public: KIETStudent() : age(0), name(“ “), cgpa(0), intake(“ “) { // empty body } void set_age(intnewage); intget_age(); };
Constructor Overloading • Constructor Overloading meand creating more than one constructor • There is always a default constructor plus any additional constructors • For e.g. you want to intialize the variable with your own set of values while creating instance • Something like this • KIETStudent S1(”Ali Khan”, 25, 3.01, ”FALL09”); • Instead of • KIETStudent S1;
Constructor Overloading class KIETStudent { private: int age; char *name; double cgpa; char *intake; public: KIETStudent() : age(0), name(“ “), cgpa(0), intake(“ “) { // empty body } KIETStudent(char *new_name, intnew_age, double new_cgpa, char *new_intake) : name(new_name), intake(new_intake), age(new_age), cgpa(new_cgpa) { // empty body } intget_age(); };