Professional Documents
Culture Documents
Introduction to Classes-Part II
(Constructors)
Lab Objectives:
1. Understand the concept of constructors
2. Learn and practice types of constructors
3. Learn Constructor Overloading
Software Required:
Dev C++
Constructors
Constructors are special class member functions which perform initialization of every object. The
Compiler calls the Constructor whenever an object is created. Constructors initialize values to object
members after storage is allocated to the object.
Types of Constructors
class_name ()
{ Constructor Definition }
Example 1
#include <iostream>
using namespace
std; class construct
{ public:
int a, b;
construct( // Default
) Constructor
{
a = 10;
b = 20; } };
int main() {
construct c;// Default constructor called automatically when the object is created cout
<< "a: "<< c.a << endl << "b: "<< c.b;
return 1;
}
Parametrized Constructor
Intensive Programming Lab 4
These are the constructors with parameter. Using this Constructor you can provide different values to
data members of different objects, by passing the appropriate values as argument.
Example 2
#include<iostream>
class Point {
int x, y;
public:
x = x1;
y = y1;
int getX() {
return x;
int getY() {
return y;
} };
int main() {
cout << "p1.x = " << p1.getX() << ", p1.y = " << p1.getY();
return 0;
}
Intensive Programming Lab 4
Constructor Overloading
Every constructor has same name as class name but they differ in terms of either number of
arguments or the datatypes of the arguments or the both.
As there is more than one constructor in class it is also called multiple constructors.
Example 3
#include <iostream>
using namespace std;
class ABC {
private: int x,y;
public:
ABC () //constructor 1 with no arguments
{
x = y = 0;
}
ABC(int a) //constructor 2 with one argument
{
x = y = a;
}
ABC(int a,int b) //constructor 3 with two argument
{
x = a; y = b;
}
void display() {
cout << "x = " << x << " and " << "y = " << y << endl;
} };
int main() {
ABC cc1; //constructor 1 ABC cc2(10); //constructor 2
ABC cc3(10,20); //constructor 3
cc1.display();
cc2.display();
cc3.display(); return 0;
}
Intensive Programming Lab 4
Practice Exercise
Q1: Write a C++ program that input two integers in main function and pass them to default
constructor of the class Add. Show the result of the addition of two numbers using a member function
named addition.
Q2: Write a c++ program for matrix multiplication with following specifications
a. Use constructor to input the no. of rows and no. of columns for matrix
b. Use getdata() function to input values for matrix
c. Use show() to display the matrix
d. Use mul() to multiply two matrices
Pseudo code:
matrix
r,c
matrix()
void getdata()
void show()
mul()
Testing
Test
case for Example 2
…………. x = 0 and y = 0
x = 10 and y = 10
x= 10 and y = 20
Test
case for Practice Q1