0% found this document useful (0 votes)
21 views19 pages

OOP Lab 05

Uploaded by

Asmara Minhas
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views19 pages

OOP Lab 05

Uploaded by

Asmara Minhas
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

UNIVERSITY OF CHAKWAL

DEPARTMENT OF COMPUTER SCIENCE


(Object Oriented Programming)

Lab 05

C++ Constructors

Lab Instructor: Engr. Samina Bilquees


Constructors in C++
Constructor in C++ is a special method that is invoked automatically at the time
of object creation. It is used to initialize the data members of new objects
generally. The constructor in C++ has the same name as the class or
structure. Constructor is invoked at the time of object creation. It constructs the
values i.e. provides data for the object which is why it is known as constructors.
Constructor does not have a return value, hence they do not have a return type.
The prototype of Constructors is as follows:
<class-name> (list-of-parameters);
Constructors can be defined inside or outside the class declaration:-

The syntax for defining the constructor within the class:


<class-name> (list-of-parameters) { // constructor definition }
The syntax for defining the constructor outside the class:
<class-name>: :<class-name> (list-of-parameters){ // constructor
definition}

Example-1

// defining the constructor within the class

#include <iostream>
using namespace std;

class student {
int rno;
char name[10];
double fee;

public:
student()
{
cout << "Enter the RollNo:";
cin >> rno;
cout << "Enter the Name:";
cin >> name;
cout << "Enter the Fee:";
cin >> fee;
}
void display()
{
cout << endl << rno << "\t" << name << "\t" << fee;
}
};

int main()
{
student s; // constructor gets called automatically when
// we create the object of the class
s.display();

return 0;
}

OUPUT

Example-2

// defining the constructor outside the class

#include <iostream>
using namespace std;
class student {
int rno;
char name[50];
double fee;

public:
student();
void display();
};

student::student()
{
cout << "Enter the RollNo:";
cin >> rno;

cout << "Enter the Name:";


cin >> name;

cout << "Enter the Fee:";


cin >> fee;
}
void student::display()
{
cout << endl << rno << "\t" << name << "\t" << fee;
}

int main()
{
student s;
s.display();

return 0;
}

OUPUT

How constructors are different from a normal member function?


A constructor is different from normal functions in following ways:
 Constructor has same name as the class itself
 Default Constructors don’t have input argument however, Copy and
Parameterized Constructors have input arguments
 Constructors don’t have return type
 A constructor is automatically called when an object is created.
 It must be placed in public section of class.
 If we do not specify a constructor, C++ compiler generates a default
constructor for object (expects no parameters and has an empty body).

Example-3

#include <iostream>
using namespace std;

class Line {
public:
void setLength( double len );
double getLength( void );
Line( double len ); //This is the constructor
private:
double length;
};
//Member function definition including constructor
Line::Line( double len ) {
cout<<"Object is being created , length ="<< len <<endl;
length = len;
}
void Line::setLength( double len ) {
length = len;
}
double Line::getLength( void ) {
return length;
}
//Main function for the program
int main() {
Line line(10.0);
//get initially set length
cout<<"Length of line :" << line.getLength() << endl;
//set line length again
line.setLength(6.0);
cout<<"Length of line :" << line.getLength() << endl;

return 0;
}

Characteristics of the constructor:

 The name of the constructor is the same as its class name.


 Constructors are mostly declared in the public section of the class
though it can be declared in the private section of the class.
 Constructors do not return values; hence they do not have a return type.
 A constructor gets called automatically when we create the object of the
class.
 Constructors can be overloaded.
 Constructor cannot be declared virtual.
 Constructor cannot be inherited.
 Addresses of Constructor cannot be referred.
 Constructor make implicit calls to new and delete operators during
memory allocation.
Types of Constructors

Let us understand the types of constructors in C++ by taking a real-world


example. Suppose you went to a shop to buy a marker. When you want to buy a
marker, what are the options. The first one you go to a shop and say give me a
marker. So just saying give me a marker mean that you did not set which brand
name and which color, you didn’t mention anything just say you want a marker.
So when we said just I want a marker so whatever the frequently sold marker is
there in the market or in his shop he will simply hand over that. And this is what
a default constructor is! The second method is you go to a shop and say I want
a marker a red in color and XYZ brand. So you are mentioning this and he will
give you that marker. So in this case you have given the parameters. And this is
what a parameterized constructor is! Then the third one you go to a shop and say
I want a marker like this(a physical marker on your hand). So the shopkeeper will
see that marker. Okay, and he will give a new marker for you. So copy of that
marker. And that’s what a copy constructor is!

Default Constructors: Default constructor is the constructor which doesn’t


take any argument. It has no parameters. It is also called a zero-argument
constructor.

// Cpp program to illustrate the concept of Constructors

#include <iostream>
using namespace std;

class construct {
public:
int a, b;

// Default Constructor
construct()
{
a = 10;
b = 20;
}
};

int main()
{
// Default constructor called automatically
// when the object is created
construct c;
cout << "a: " << c.a << endl << "b: " << c.b;
return 1;
}

Note: Even if we do not define any constructor explicitly, the compiler will
automatically provide a default constructor implicitly.

2. Parameterized Constructors: It is possible to pass arguments to


constructors. Typically, these arguments help initialize an object when it is
created. To create a parameterized constructor, simply add parameters to it the
way you would to any other function. When you define the constructor’s body,
use the parameters to initialize the object.
Note: when the parameterized constructor is defined and no default constructor
is defined explicitly, the compiler will not implicitly call the default constructor
and hence creating a simple object as

Example
// CPP program to illustrate parameterized constructors

#include <iostream>
using namespace std;

class Point {
private:
int x, y;

public:
// Parameterized Constructor
Point(int x1, int y1)
{
x = x1;
y = y1;
}

int getX() { return x; }


int getY() { return y; }
};

int main()
{
// Constructor called
Point p1(10, 15);

// Access values assigned by constructor


cout << "p1.x = " << p1.getX()
<< ", p1.y = " << p1.getY();

return 0;
}

OUPUT

Example

#include<iostream>
#include<string.h>
using namespace std;

class student
{
int rno;
char name[50];
double fee;

public:
student(int,char[],double);
void display();

};

student::student(int no,char n[],double f)


{
rno=no;
strcpy(name,n);
fee=f;
}

void student::display()
{
cout<<endl<<rno<<"\t"<<name<<"\t"<<fee;
}

int main()
{
student s(10,"Ali",1000);
s.display();
return 0;
}

OUPUT

When an object is declared in a parameterized constructor, the initial values


have to be passed as arguments to the constructor function. The normal way of
object declaration may not work. The constructors can be called explicitly or
implicitly.
Example e = Example(0, 50); // Explicit call
Example e(0, 50); // Implicit call

 Uses of Parameterized constructor:


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.

 Can we have more than one constructor in a class?


Yes, It is called Constructor Overloading.

3. Copy Constructor: A copy constructor is a member function that initializes


an object using another object of the same class.

Whenever we define one or more non-default constructors (with parameters) for


a class, a default constructor (without parameters) should also be explicitly
defined as the compiler will not provide a default constructor in this case.
However, it is not necessary but it’s considered to be the best practice to always
define a default constructor.
Copy constructor takes a reference to an object of the same class as an
argument.

Sample(Sample &t)
{
id=t.id;
}

// Implicit copy constructor

#include<iostream>
using namespace std;

class Sample
{ int id;
public:
void init(int x)
{
id=x;
}
void display()
{
cout<<endl<<"ID="<<id;
}
};

int main()
{
Sample obj1;
obj1.init(10);
obj1.display();

Sample obj2(obj1); //or obj2=obj1;


obj2.display();
return 0;
}
#include<iostream>
#include<string.h>
using namespace std;
class student
{
int rno;
char name[50];
double fee;
public:
student(int,char[],double);
student(student &t) //copy constructor
{
rno=t.rno;
strcpy(name,t.name);
fee=t.fee;
}
void display();

};

student::student(int no,char n[],double f)


{
rno=no;
strcpy(name,n);
fee=f;
}

void student::display()
{
cout<<endl<<rno<<"\t"<<name<<"\t"<<fee;
}

int main()
{
student s(1001,"Manjeet",10000);
s.display();

student manjeet(s); //copy constructor called


manjeet.display();

return 0;
}
Constructor overloading

Different constructors with the same name is called constructor overloading.


The constructor must obey one or both of the following rules.

1. All constructors with the same name have a different number of


parameters.
o For example numbers_sum(int n1, int n2) and another constructor
as numbers_sum(int n1, int n2, int n3) is legal.
2. All constructors with the same name and have the same number of
parameters but of different data types is also legal.
o numbers_sum(int n1, int n2) and another constructor as
numbers_sum(float n1, float n2).

Examples of legal and illegal constructor overloading


 numbers_sum(int n1, int n2) and numbers_sum(double n1, double n2) is
legal in constructor overloading.
 numbers_sum(int n1, int n2) and numbers_sum(int n1, double n2) is legal
in constructor overloading.
 numbers_sum(int n1, int n2) and numbers_sum(double n1, int n2) is legal
in constructor overloading.
 numbers_sum(int n1, int n2) and numbers_sum(int n1, int n2) is illegal in
constructor overloading.
 numbers_sum(double n1, double n2) and numbers_sum(double n1,
double n2) is illegal in constructor overloading.
 numbers_sum(int n1) and numbers_sum(int n1, int n2) is legal in
constructor overloading.
 numbers_sum(int n1, int n2) and numbers_sum(int n1) is legal in
constructor overloading.
Example of constructor overloading

Example of constructor overloading with a different number of parameters and constructors with the
same name.

Output
Sum of two numbers is =
7
the sum of three numbers is =
12

Example of constructors with the same name and have the same number of
parameters but of different data types.
Output
Sum of two numbers is =
7
the sum of three numbers is =
10
Example of Constructor Overloading In C++
Output
I am Constructor
Im Constructor
Values :33 +7=40
Values :3 +7=10

Advantages of constructor overloading?

1. It acts as compile-time polymorphism.


2. Objects can be constructed in different ways.
3. Helpful when we are programming the big problem because it is easy
to remember the constructor name if many constructors are with the
same name.
LAB TASKS

Q1: Write a program in C++ to convert a decimal number into binary without using an array and
using the constructor.

Q2: Write a C++ Program To calculate volume of Box using parametrized Constructor

Q3: Write a program in C++ to convert a decimal number into binary without using an
array by using the constructor overloading.
Q4: Write a program in C++ to convert a decimal number into binary without using an array
by using the constructor overloading.
Q5: Write a C++ Program to show Default copy constructor as describe in the following
output.

You might also like