Lecture 3 Constructor and Destructor
Lecture 3 Constructor and Destructor
Page 1
Al-Farabi University College
int main()
{
// create two GradeBook objects
GradeBook gradeBook1( "CS101 Introduction to C++ Programming" );
GradeBook gradeBook2( "CS102 Data Structures in C++" );
// display initial value of courseName for each GradeBook
cout << "gradeBook1 created for course: " <<gradeBook1.getCourseName()
<< "\ngradeBook2 created for course: " <<gradeBook2.getCourseName()
<< endl;
system("pause");
} // end main
The output is
Notes
The constructor should be declared in the public section.
The constructor does not have return type, (not even void),
and therefore it cannot return any value.
There is no need to write any statement to invoke the
constructor function because it is invoked automatically
when the object is created.
A constructor that accepts no arguments is called the default
constructor.
If no constructor is defined, then the compiler creates an
implicit constructor.
The constructor can take arguments like other C++ functions.
This is called parameterized constructor.
Page 2
Al-Farabi University College
Parameterized Constructors
Sometimes we need to initialize the data elements of different
objects with different values when they are created. This can be
done by passing arguments to the constructor function when
objects are created. Such constructor is called parameterized
constructor.
#include <iostream>
using namespace std;
class integer
{
private:
int m, n;
public:
integer(int , int ); //parameterized constructor
void printdata();
};
integer :: integer(int x, int y)
{ m = x; n = y; }
void integer :: printdata()
{
cout << "m = " << m << "\n"
<<"n = " << n << "\n";
}
void main()
{
integer intl(1, 100);
intl.printdata();
system("pause");
}
Destructors
Page 3
Al-Farabi University College
Page 4
Al-Farabi University College
Page 5
Al-Farabi University College
// qasim.cpp
// Including class GradeBook from file GradeBook.h for use in main.
#include <iostream>
#include "GradeBook.h" // include definition of class GradeBook
using namespace std;
// function main begins program execution
int main()
{
// create two GradeBook objects
GradeBook gradeBook1( "CS101 Introduction to C++ Programming" );
GradeBook gradeBook2( "CS102 Data Structures in C++" );
// display initial value of courseName for each GradeBook
cout << "gradeBook1 created for course: " <<
gradeBook1.getCourseName()
<< "\ngradeBook2 created for course: " << gradeBook2.getCourseName()
<< endl;
} // end main
Page 6