Object Oriented Programming: Chapter 2: Classes and Objects

Types of Constructors

C++ Programming | Object Oriented Programming

Various s types of constructors used in C++ are ‒ 1. Default constructor 2. Parameterized constructor 3. Default argument constructor 4. Copy constructor. Let us discuss them in detail. - with example C++ Programs.

Types of Constructors

 

Types of Constructors

• Various s types of constructors used in C++ are ‒

1. Default constructor

2. Parameterized constructor

3. Default argument constructor

4. Copy constructor.

Let us discuss them in detail.


1. Default Constructor

• This is the simplest way of defining the constructor. We simply define the constructor without passing any argument to it.

C++ Program

#include<iostream>

using namespace std;

class image

{

private:

int height, width;

public:

image() // Constructor is defined. Note that name of the constructor is similar to the name of the class. Purpose of constructor is to initialize the variables

{

        height=0;

        width=0;

}

int area()

{

        cout<<"Enter the value of height"<<"\n";

        cin>>height;

        cout<<"Enter The value of width"<<"\n";

         cin>>width;

        return (height*width);

}

};

int main() //object is created and values are initialized. When object gets created the compiler invokes the constructor image() 

{

        image obj1;

        cout<<"The area is :"<<obj1.area()<<endl;

        return 0;

}

Output

Enter the value of height

10

Enter The value of width

 20

The area is:200


2. Parameterized Constructor

Another way of defining the constructor is by passing the parameters.

We can call the parameterised constructor using

1. Implicit call

2. Explicit call

For example:

Here an object obj1 gets created by passing the parameters 5 and 3 for the class image.

image obj1(5,3); < ‒‒‒‒‒‒‒‒‒‒‒‒‒‒‒‒‒‒‒‒‒‒‒‒‒‒‒Implicit call

image obj1 = image(5,3); < ‒‒‒‒‒‒‒‒‒‒‒‒‒‒‒‒‒‒‒ Explicit call

Most commonly use of implicit call is preferred in parameterised constructor. Following program makes use of parameterised constructor.

C++ Program

#include<iostream>

using namespace std;

class image

{

private:

       int height, width;

public:

       image(int x, int y) //constructor

       {

              height=x;

              width=y

       }

       int area()

       {

              return (height*width);

       }

};

int main()

{

       image obj1(5,3);

       cout<<"The area is :"<<obj1.area()<<endl;

       return 0;

}

Output

The area is :15

Program Explanation: In above program

• The parameterized constructor image(int x, int y) is defined. This is a type of constructer to which the arguments or parameters are passed.

• Note that this constructor need to be defined explicitly.

Example :1

Write a program to add 2 distance objects (Use constructor to initialize one of the 2 distance objects).

Solution:

#include<iostream>

using namespace std;

class Distance

{

int feet, inch;

public:

Distance()

{

Feet = 0;

inch = 0;

}

Distance(int f,int i)

{

feet = f;

inch = i;

}

void read_dist();

void display();

void add(Distance, Distance);

};

void Distance::read_dist()

{

    cout << "Enter distance(feet and inches) :";

    cin >> feet >> inch;

}

void Distance::display()

{

    cout << "Distance Feet: << feet << ", Inches : " << inch << "\n";

}

void Distance::add(Distance x, Distance y)

{

    inch = x.inch + y.inch;

    feet = x.feet + y.feet;

    if (inch >= 12)

    {

        feet = x.feet + y.feet + (inch / 12);

        inch = inch % 12;

    }

}

int main()

{

    Distance d1, d3;

    Distance d2(24, 14);

    d1.read_dist();

    cout << "Second distance is entered by defualt arguments : \n";

    d1.display();

    d2.display();

    cout << "\n Addition of two distances: \n";

    d3.add(d1, d2);

    d3.display();

    return 0;

}

Output

Enter distance(feet and inches) :25 32

Second distance is entered by default arguments:

Distance Feet : 25, Inches : 32

Distance Feet : 24, Inches : 14

Addition of two distances :

Distance Feet : 52, Inches : 10

Example : 2

Write a C++ program to calculate surface area and volume of sphere using equations 4r2  and 4/3 r3 where r is radius of the sphere. Use class named sphere and object 'mysphere' and member functions as vol() and s‒area().

Solution :

#include<iostream>

using namespace std;

#define pi 3.14

class Sphere

{

private:

int r;

public:

void get_radius();

void vol();

void s area();

};

void Sphere::get_radius()

{

       cout<<"\n Enter radius: ";

        cin>>r;

}

void Sphere::vol()

{

       float v;

       v=pi*r*r*r*(4/3);

       cout<<"\nVolume: "<<v;

}

void Sphere::s_area()

{

       float a;

       a=pi*r*r*4;

       cout<<"\nArea: "<<a;

}

int main()

{

       Sphere mysphere;

       mysphere.get_radius();

       mysphere.s_area();

       mysphere.vol();

       return 0;

}


3. Overloaded Constructor

• The overloaded constructor can be defined by more than one functions with the same name but having different number of parameters. For instance we can have image();

image(int,int);

both the functions in the same program. Let us have the overloaded constructor in the following program ‒

C++ Program

#include<iostream>

using namespace std;

class image

{

private:

        int height, width;

 public:

         image (int, int);//constructor

        image();//another constructor

         int area();//regular function

};

image::image(int x,int y)//First constructor

{

        height=x;

        width=y;

}

image::image()//second constructor

{

        width=7;

        height=4;

}

int image::area()

{

        return (height*width);

}

void main()

{

        clrscr();

         image obj1(10,20);

        image obj2;

        cout<<"The area is :"<<obj1.area()<<endl;

        cout<<"\tFollowing area is obtained by another

        constructor"<<endl;

        cout<<"The area is :"<<obj2.area()<<endl;

        getch();

}

Output

The area is :200

                Following area is obtained by another constructor

The area is :28

Program Explanation: In above program

•  We have achieved overloaded constructors by defining two constructors having same name but different number of parameters.

•  One constructor is default constructor and another is a parameterised constructor.


4. Copy Constructor

•  The copy constructor is called whenever a new variable is created from an object.

 • In C++ the copy constructor is created when the copy of existing object needs to be created. Usually the compiler creates a copy constructor for each class when no copy constructor is defined. Such a constructor is called implicit constructor and when the copy constructor is explicitly created in the program then it is called explicit constructor.

Definition: Copy constructor is a special type of constructor in which new object is created as a copy of existing object.

• In other words in copy constructor one object is initialized by the other object. The general form of copy constructor is ‒

classname (classname &object)

{

    //body of the constructor

}

While invoking the copy constructor we will use following syntax

classname new_object_name(old_object_name);

• Thus the copy constructor takes a reference to an object of same class as an argument.

C++ Program

#include<iostream>

using namespace std;

class test

{

int x;

        public:

        //default constructor

         test();

        //parameterized constructor

        test(int val)

        {

                x=val;

        }

        //copy constructor

        test(test &obj)

        {

                x=obj.x;//entered the value in obj.x

        }

        void show()

        {

                cout<<x;

        }

};

int main()

{

int val;

cout<<"Enter some number"<<endl;

cin>>val;

test Old(val);

//call for copy constructor

test New(Old); <‒‒‒‒ object 'Old' is passed as argument to object 'New'

 cout<<"\n The original value is: ";

Old.show();

cout<<"\n The New copied value is: ";

New.show();

cout<<endl;

return 0;

}

Output

Enter some number

500

The original value is : 500

The New copied value is : 500

Program Explanation:

In above program there are three constructors first one is the simple constructor and second constructor is a constructor in which parameter is passed. The copy constructor is always declared by passing reference parameter to it. And the reference variable is given by '&'. We can not pass the parameter by value to copy constructor.


5. Programs Based on Constructors

Example :3

Write a class called "arithmetic" having two integer and one character data members. It performs the operation on its integer members indicated by character member (+,‒,*,/) For example * indicates multiplication on data members as d1*d2. Write a class with all necessary constructors and methods to perform the operation and print the operation performed in format Ans= d1 op d2. Test your class using main()

Solution:

#include<iostream>

using namespace std;

class Arithmetic

{

int d1,d2;

char op;

public:

Arithmetic(int x,char c,int y)

{

    d1=x;

    d2=y;

    op=c;

}

int operation()

{

int c;

switch(op)

{

case '+':c=d1+d2;

    break;

case '‒':c=d1‒d2;

    break;

case "*':c=d1*d2;

    break;

case '/':c=d1/d2;

    break;

}

return c;

}

};

void main()

{

     Arithmetic obj1(10,'+',20);

     Arithmetic obj2(20,'‒',10);

    Arithmetic obj3(10,'/',5);

    Arithmetic obj4(10,'*',20);

    cout<<"\n Addition of 10+20= "<<obj1.operation();

    cout<<"\n Subtraction of 20‒10= "<<obj2.operation();

    cout<<"\n Division of 10/5= "<<obj3.operation();

    cout<<"\n Multiplication of 10*20= "<<obj4.operation();

}

Output

Addition of 10+20= 30

Subtraction of 20‒10= 10

Division of 10/5= 2

Multiplication of 10*20= 200

Example :4

Discuss nameless temporary object.

Solution: The nameless temporary objects are the objects created without name.

For example ‒ Consider a class Rectangle. If we want to pass the nameless object of this class to function compute‒area then it can be written as compute‒area (Rectangle (10, 20));

Example :5

Write a program which include class to represent a vector (a series of float values). Include member functions to program the following tasks:

a) To create the vector

b) To modify the value of given elements

c) To display the given vector in the form (10,20,30).

Solution :

#include<iostream>

using namespace std;

class Vect

{

float a[10];

int n;

public:

void create()

{

    cout<<"\n How elements are there in a vector?";

    cin>>n;

    for(int i=0;i<n;i++)

    {

            cout<<"\nEnter element "<<i+1<<"";

            cin>>a[i];

    }

}

void modify()

{

    int index;

    float new_element;

    cout<<"\n Enter the position of the element to be modified ";

    cin>>index;

    cout<<"\n Enter the new element ";

    cin>>new_element;

    a[index‒1]=new_element;

}

void display()

{

    cout<<"(";;

    for(int i=0;i<n;i++)

            cout<<a[i]<<",";

    cout<<")";

}

};

void main()

{

    Vect obj;

    obj.create();

    obj.display();

    obj.modify();

    obj.display();

}

Output

How elements are there in a vector?3

Enter element 1 10

Enter element 2 20

Enter element 3 30

(10,20,30,)

Enter the position of the element to be modified 3

Enter the new element 50

(10,20,50,)

Example : 6

What is constructor? Write the characteristics of constructor function. Define class named point which represents 2‒D point, i.e P(x, y). Define default constructor to initialize both data member value 5, parameterized constructor to initialize member according to value supplied by user and copy constructor. Define necessary function and write a program to test class Point.

Solution:

Constructor and its characteristics : Refer previous section.

Programming Example :

#include<iostream>

using namespace std;

class Point

{

private:

    int x,y;

public:

    Point(int,int);//Parameterized constructor

    Point();//default constructor

    Point(Point &ob);

    void display();//regular function

};

Point::Point(int a,int b)//Parameterized constructor defined

{

    x=a;

    y=b;

}

Point::Point()//default constructor defined

{

    x=5;

    y=5;

}

Point::Point(Point &ob)//copy constructor defined

{

    x=ob.x;

    y=ob.y;

}

void Point::display()

{

    cout<<"\n x= "<<x;

    cout<<"\n y= "<<y;

}

void main()

{

    Point obj1;

    int val1,val2;

    cout<<"\n Point denoted using default constructor: ";

    obj1.display();

    cout<<"\n Enter the value of x: ";

    cin>>val1;

    cout<<"\n Enter the value of y: ";

    cin>>val2;

    cout<<"\n Point denoted using Parameterized constructor: ";

    Point obj2(val1,val2);

    obj2.display();

    cout<<"\n Point denoted using Copy constructor: ";

    Point obj3(obj2);//copying the object using copy constructor

    obj3.display();

    cout<<endl;

}

Example : 7

Declare a class called book_details to represent details for a book, having data members like title, author, edition, price and no_of_copies_available. Define following functions:

‒  constructor(s)

‒ display to display all data members

‒ find_books to find and display details of all books having price less than 250 main to create an array of book_details and to show usage of above functions.

Solution :

#include <iostream>

#include<cstring>

 using namespace std;

 #define size 30

class book_details

{

private:

    char title[size];

    char author[size];

    int edition;

    double price;

    int no_of_copies_available;

public:

    book_details() {}

    book_details(char title[], char author[], int edition, double price, int

    no_of_copies_available);

    void display();

    void find_books();

};

book_details::book_details(char t[], char ath[], int ed, double p, int num)

{

    strcpy(title,t);

    strcpy(author, ath);

    edition = ed;

    price = p;

    no_of_copies_available = num;

}

void book_details::display()

{

    cout<<"\nTitle: "<<title;

    cout << "\nAuthor: " << author;

    cout<<"\nEdition: " << edition;

    cout << "\nPrice: " << price;

    cout << "\nNo of Copies: " << no_of_copies_available;

}

void book_details::find_books()

{

    if (price < 250)

    {

        cout << "\nTitle: " << title;

        cout << "\nAuthor: << author;

         cout << "\nEdition: " << edition;

        cout << "\nPrice: << price;

        cout << "\nNo of Copies: " << no_of_copies_available;

    }

}

int main()

{

 book details bk[3];

 cout << "Program For Book Details";

int i;

char t[size];

char ath[size];

int ed;

double p;

int num;

cout << "\n\t\t ENTER BOOK DETAILS ";

for (i = 0; i < 3; i++)

{

    cout << "\n Enter title: ";

    cin.getline(t,30);

    cout << "\n Enter author: ";

    cin.getline(ath,30);

    cout << "\n Enter edition: ";

    cin >> ed;

    cout << "\n Enter price(in Rs.): ";

    cin >> p;

    cout << "\n Enter no of copies: ";

    cin >> num;

    bk[i] = book_details(t, ath, ed, p, num);

}

cout << "\n Display Complete Book Record";

for (i = 0; i < 3; i++)

{

    bk[i].display();

}

cout << "\n Display the Book Record having Price less than Rs.250";

 for (i = 0; i < 3; i++)

{

    bk[i].find_books();

}

return 0;

}

Example : 8

 Can we have more than one constructor in a class? If yes explain the need for such a situation.

Solution:

• Yes we can have more than one constructor in a class.

•  The mechanism by which more than one constructors are defined is called the constructor overloading.

•  Constructor is a special function having the same name as its class name.

• In such situation, all the constructors have the same name as the corresponding class but differ only in terms of their signature (in terms of the number of arguments, or data types of their arguments, or both). Hence all these constructors need to be defined explicitly so that when any object gets created appropriate constructor function can be called.

Example : 9

 Distinguish between following two statements:

Time T2(T1);

Time T2= T1;

T1 and T2 are objects of Time class.

Solution :

1) Time T2 (T1): Here object T1 is passed as a parameter. Hence it is implicit call to copy constructor.

2) Time T2=T1; Here T1 is directly assigned to T2. Hence it is an explicit call to copy constructor.

Example: 10

 Declare a class called bird having private data members name and weight. Define following functions: ‒ default constructor for reading data members from key board ‒ overloaded constructor with two arguments to be used for initialization of data members. ‒ display function to display data members. ‒ overloaded member operator >= to compare weight of two bird objects, returning false if weight of first bird object is less than that of the second and true otherwise. Define main to illustrate use of above functions.

Solution :

#include<iostream>

 #include<cstring>

using namespace std;

class bird

{

private:

    char *name;

    float weight;

public:

    bird(){}//default constructor

    bird (char *n, float w)//overloaded constructor

    {

        name = n;

        weight = w;

    }

    void display() //display function

    {

        cout << "\n Name: << name;

        cout << "\n Weight: " << weight;

    }

    friend int operator >= (bird b1, bird b2);//overloaded member operator

};

int operator >=(bird b1, bird b2)

{

    if (b1.weight >= b2.weight)

        return 1;

    else

        return 0;

}

int main()

{

char name1[10], name2[10];

float wt1, wt2;

cout << "\n Enter the name of First Bird: ";

cin >> name1;

cout << "\n Enter the weight First Bird: ";

 cin >> wt1;

cout << "\n Enter the name of Second Bird: ";

cin >> name2;

cout << "\n Enter the weight Second Bird: ";

cin >> wt2;

bird obj1(name1,wt1);

bird obj2(name2, wt2);

obj1.display();

obj2.display();

if (obj1 >= obj2)

    cout << "\n Weight of First bird is greater than or equal to second bird";

else

    cout << "\n Weight of First bird is lesser than second bird";

return 0;

}

Example: 11

Following is a main() program where time is a class which contains variables hrs and minutes duration stores total time in minutes. Define a class time with necessary functions to break up the duration in maximum hours and remaining minutes and store them into hrs and minutes respectively.

void main()

{

time T1;

int duration = 85;

T1 = duration;

}

Solution :

class time

{

int hours;

int minutes;

public:

time(){}

time(int t)

{

    hours=t/60;

    minutes=t%60;

}

void showtime()

{

    cout<<hours<<"hrs "<<minutes<<"min";

}

};

Example: 12

 Write a program to illustrate multiple constructors and default argument for a single class.

Solution :

#include<iostream>

using namespace std;

class image

{

private:

    int height,width;

public:

    image(int x=4,int y=0);       //Default argument

    void display();

};

image::image(int x,int y)      //Another constructor

{

    height=x;

    width=y;

}

void image::display()

{

    cout<<"\nheight: "<<height;

    cout<<"\nwidth: "<<width;

}

void main()

{

    image obj1(10,20);

    image obj2;

    cout<<"\n Another constructor is: ";

    obj1.display();

    cout<<"\n\t Default argumented constructor";

    obj2.display();

}

Output

Another constructor is:

height: 10

width: 20

Default argumented constructor

height: 4

width: 0

Example: 13

 Write a C++ program to perform 2D matrix operations as follows ‒

i) Define class MATRIX, use appropriate constructors

ii) Define methods for the following two matrix operations: Determinant and transpose.

 iii) Write a main program to demonstrate the use of MATRIX class and its methods.

Solution :

#include<iostream>

using namespace std;

#define SIZE 10

class MATRIX

{

public:

float a[SIZE][SIZE],value,n;

 void getdata(float a[][SIZE],int n);

int ChkDiagonal(float a[][SIZE],int n);

 float Determ(float a[][SIZE],int n);

void Transpose(float a[][SIZE], int n);

};

void MATRIX::getdata(float a[][SIZE], int n)

{

int i,j;

cout<<"Enter order of Matrix: ";

cin>>n;

for(i=0;i<n;i++)

{

   for(j=0;j<n;j++)

   {

      cout<<"Enter the matrix element";

       cin>>a[i][j];

   }

}

cout<<"\n\t\t Transpose of Matrix\n";

Transpose(a,n);

cout<<"\n\t\t Determinant of Matrix\n";

if(ChkDiagonal(a,n)= =0)

   value=0;

else

   value=Determ(a,n);

cout<<"Determinant Value :"<<value;

}

float MATRIX::Determ(float a[][SIZE],int n)

{

int i,j,k;

float multiplier;

float d=1;

10

for(i=0;i<n;i++)

{

for(j=0;j<n;j++)

{

   multiplier =a[j][i]/a[i][i];

   for(k=0;k<n;k++)

   {

      if(i= =j) break;

      alj][k]=a[j][k]‒a[i][k]*multiplier;

   }

}

}

for(i=0;i<n;i++)

{

   d=d*a[i][i];

return(d);

}

int MATRIX::ChkDiagonal(float a[][SIZE], int n)

{

int i,j,k;

for(i=0;i<n;i++)

if(a[i][i]==0)

{

   for(j=0;j<n;j++)

   {

      if(a[i][j]!=0)

      {

            k=j;

            break;

      }

      if(j= =(n))

            return(0);

   }

for(j=0;j<n;j++)

{

      a[j][i]=a[j][i]‒a[j][k];

}

}

}

return(1);

}

void MATRIX::Transpose(float a[SIZE][SIZE], int n)

{

int i,j;

float b[SIZE][SIZE];

cout<<"\n The original Matrix is:\n";

for(i=0;i<n;i++)

{

for(j=0;j<n;j++)

{

cout<<""<<a[i][j];

}

cout<<"\n";

}

for(i=0;i<n;i++)

{

for(j=0;j<n;j++)

{

b[j][i]=a[i][j];

}

}

cout<<"\n The Transposed Matrix is:\n";

 for(i=0;i<n;i++)

{

for(j=0;j<n;j++)

{

cout<<" "<<b[i][j];

}

cout<<"\n";

}

}

void main()

{

MATRIX obj;

obj.getdata(obj.a,obj.n);

getch();

}

Output

Enter order of Matrix :3

 Enter the matrix element2

 Enter the matrix element‒2

Enter the matrix element0

Enter the matrix element‒1

 Enter the matrix element5

 Enter the matrix element1

 Enter the matrix element3

Enter the matrix element4

Enter the matrix element5

           Transpose of Matrix

The original Matrix is:

2 ‒2 0

‒1 5 1

3 4 5

The Transposed Matrix is:

2 ‒1 3

‒2 5 4

0 1 5

           Determinant of Matrix

            Determinant Value :26

Example: 14

 Write a C++ program to define overloaded constructor to perform string initialization, string copy and string destruction.

Solution :

#include<iostream>

#include<cstring>

using namespace std;

class test

{

private:

     char *str;

public:

     test(char *str);//constructor

     test();//another constructor

     ~test();//destructor

     void display();//regular function

};

test::test(char *s)//First constructor

{

     str=new char;

     str=s;

}

test::test()//second constructor for copying

{

     str="India";

}

mdomn

test::~test()

{

     str=NULL;//erasing the contents of string

     delete str;//de‒allocating the memory

}

void test::display()

{

     cout<<"\n The string is "<<str;

}

void main()

{

test obj1("Hello");

test obj2;

obj1.display();

cout<<"\nFollowing string is obtained by another constructor"<<endl;

obj2.display();

cout<<endl;

}

Output

The string is Hello

Following string is obtained by another constructor

The string is India

Example 2.6.15

 Write a C++ program to generate Fibonacci using copy constructor.

Solution :

#include<iostream>

using namespace std;

class Fib

{

int a,b,n;

public:

Fib();

Fib(int val)

{

n=val;

}

Fib(Fib &obj)

{

n=obj.n;

}

void display()

{

a=1;b=1;

cout<<a<<" "<<b;

for(int i=2;i<n;i++)

{

int c;

c=a+b;

a=b;

b=c;

cout<<" "<<c;

}

}

};

void main()

{

int val;

cout<<"\n Enter the limit of Fibonacci Series: ";

cin>>val;

Fib obj1(val);

Fib obj2(obj1); //invoking copy constructor

obj2.display();

}

Output

Enter the limit of Fibonacci Series: 7

1 1 2 3 5 8 13

 

Object Oriented Programming: Chapter 2: Classes and Objects : Tag: Oops, Computer Programming : C++ Programming | Object Oriented Programming - Types of Constructors


Object Oriented Programming: Chapter 2: Classes and Objects



Under Subject


Object Oriented Programming (OOPs)

CS25C07 2nd Semester CSE, CSE(CY) Depts | 2025 Regulation | 2nd Semester 2025 Regulation



Related Subjects


English Essentials II

EN25C02 2nd Semester | 2025 Regulation | 2nd Semester 2025 Regulation



Linear Algebra

MA25C02 2nd Semester | 2025 Regulation


Applied Physics (CSIE) II

PH25C03 2nd Semester AIDS, CSE, IT, CSE(CY) Dept | 2025 Regulation | 2nd Semester 2025 Regulation


Digital Principles and Computer Organization

CS25C06 2nd Semester AIDS, CSE, IT, CSE(CY) Dept | 2025 Regulation | 2nd Semester 2025 Regulation


Basic Electrical and Electronics Engineering

EE25C01 2nd Semester | 2025 Regulation | 2nd Semester 2025 Regulation


Object Oriented Programming (OOPs)

CS25C07 2nd Semester CSE, CSE(CY) Depts | 2025 Regulation | 2nd Semester 2025 Regulation


Re-Engineering for Innovation

ME25C05 2nd Semester | 2025 Regulation | 2nd Semester 2025 Regulation


Object Oriented Programming (OOPs) - Laboratory

CS25C07 2nd Semester CSE, CSE(CY) Depts | 2025 Regulation | 2nd Semester 2025 Regulation