Understanding Constructors in Programming Paradigms: A Lecture by Hamza Azeem
80 likes | 194 Views
Constructors are vital in class initialization, learn how to use them effectively to initialize variables, and explore constructor overloading for advanced object creation in programming paradigms.
Understanding Constructors in Programming Paradigms: A Lecture by Hamza Azeem
E N D
Presentation Transcript
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(); };