Constructors
Constructors
Abeer Mohammed
Computer Engineering Department -2nd Stage Al- Esraa University Collage
Constructor in C++
What is constructor in C++ programming and its purpose?
The main purpose of the class constructor is to construct an object of the class. In other word, it
is used to initialize all class data members.
1
Object Oriented Programing MSc. Abeer Mohammed
Computer Engineering Department -2nd Stage Al- Esraa University Collage
2
Object Oriented Programing MSc. Abeer Mohammed
Computer Engineering Department -2nd Stage Al- Esraa University Collage
#include <iostream>
using namespace std;
class Point
{
private:
int a, b;
public:
Point(int i, int j) // Parameterized Constructor
{
a = i;
b = j;
}
void show()
{
cout<<"a=" <<a<<endl;
cout<<"b=" <<b<<endl;
}
};
int main()
{
Point p1(10, 15); // Constructor called
p1.show();
return 0;
}
Output:
3
Object Oriented Programing MSc. Abeer Mohammed
Computer Engineering Department -2nd Stage Al- Esraa University Collage
1. It is used to initialize the various data elements of different objects with different values
when they are created.
2. It is used to overload constructors.
A constructor that initializes an object using values of another object
passed to it as parameter, is called copy constructor. It creates the copy
of the passed object.
Home Work
1. Design OOP program that include class name (Room) as illustrated in following chart ,
then create object from the int main that using constructor to assigning private values and
calling, show()
2. Design OOP program that include class name (Distance) as illustrated in following chart ,
then create object from the int main that using constructor to assigning private values and
calling, getdist(), showdist()