Docsity

Constructor, Constructor Overloading - Object Oriented Programming - Lecture Slides, Slides of Object Oriented Programming

Partial preview of the text

Download Constructor, Constructor Overloading - Object Oriented Programming - Lecture Slides and more Slides Object Oriented Programming in PDF only on Docsity!

Object Oriented Programming

(OOP)

Lecture No. 8

Constructor

Constructor (contd.)

  • Constructor is a special function having same name as the class name
  • Constructor does not have return type
  • Constructors are commonly public members

Example

class Student{

…

public:

Student(){ rollNo = 0; … }

};

Default Constructor

  • Constructor without any argument is called default constructor
  • If we do not define a default constructor the compiler will generate a default constructor
  • This compiler generated default constructor initialize the data members to their default values

Example

class Student

{

int rollNo; char *name; float GPA;

public:

… //no constructors

};

Constructor Overloading

  • Constructors can have parameters
  • These parameters are used to initialize the data members with user supplied data

Example

class Student{ … public: Student(); Student(char * aName); Student(char * aName, int aRollNo); Student(int aRollNo, int aRollNo, float aGPA); };

Example

int main()

{

Student student1; Student student2(“Name”); Student student3(”Name”, 1); Student student4(”Name”,1,4.0);

}

Constructor Overloading

  • Use default parameter value to reduce the writing effort

Copy Constructor

  • Copy constructor are used when:
    • Initializing an object at the time of creation
    • When an object is passed by value to a function

Example

void func1(Student student){

…

}

int main(){

Student studentA; Student studentB = studentA; func1(studentA);

}

Shallow Copy

  • When we initialize one object with another then the compiler copies state of one object to the other
  • This kind of copying is called shallow copying

Example

Student studentA; Student studentB = studentA;

Name

GPA

RollNo

studentA

Name

GPA

RollNo

studentB A H M A D …

Memory