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

Object Oriented Programming Lab 4

Uploaded by

Muhammad Fareed
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
21 views15 pages

Object Oriented Programming Lab 4

Uploaded by

Muhammad Fareed
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 15

Object Oriented Programming Lab

Lab Manual (Lab 4)

School of Systems and Technology


UMT Lahore Pakistan
Objective:
The objective of this lab is to cover:

 C++ Constructor
 Constructor Parameter
 Constructors (Overloaded Constructors)
 Copy Constructors
 Destructors

C++ Constructors
A constructor in C++ is a special method that is automatically called when an object of a class is
created.

To create a constructor, use the same name as the class, followed by parentheses ():

Sample Code:

#include <iostream>
using namespace std;

class MyClass { // The class


public: // Access specifier
MyClass() { // Constructor
cout << "Hello World!";
}
};

int main() {
MyClass myObj; // Create an object of MyClass (this will call the constructor)
return 0;
}
Output:

Note: The constructor has the same name as the class, it is always public, and it does not have
any return value.

Constructor Parameters
Constructors can also take parameters (just like regular functions), which can be useful for
setting initial values for attributes.

Sample Code:

#include <iostream>
using namespace std;

class Car { // The class


public: // Access specifier
string brand; // Attribute
string model; // Attribute
int year; // Attribute
Car(string x, string y, int z) { // Constructor with parameters
brand = x;
model = y;
year = z;
}
};

int main() {
// Create Car objects and call the constructor with different values
Car carObj1("BMW", "X5", 1999);
Car carObj2("Ford", "Mustang", 1969);

// Print values
cout << carObj1.brand << " " << carObj1.model << " " << carObj1.year << "\n";
cout << carObj2.brand << " " << carObj2.model << " " << carObj2.year << "\n";
return 0;
}

Output:

Note:
Just like functions, constructors can also be defined outside the class. First, declare the
constructor inside the class, and then define it outside of the class by specifying the name of
the class, followed by the scope resolution :: operator, followed by the name of the constructor
(which is the same as the class):
Example:

#include <iostream>
using namespace std;

class Car { // The class


public: // Access specifier
string brand; // Attribute
string model; // Attribute
int year; // Attribute
Car(string x, string y, int z); // Constructor declaration
};

// Constructor definition outside the class


Car::Car(string x, string y, int z) {
brand = x;
model = y;
year = z;
}

int main() {
// Create Car objects and call the constructor with different values
Car carObj1("BMW", "X5", 1999);
Car carObj2("Ford", "Mustang", 1969);

// Print values
cout << carObj1.brand << " " << carObj1.model << " " << carObj1.year << "\n";
cout << carObj2.brand << " " << carObj2.model << " " << carObj2.year << "\n";
return 0;
}

Output:

C++ Constructor Overloading


In this Lab, we will learn about constructor overloading in C++ with the help of examples.

Constructors can be overloaded in a similar way as function overloading.

Overloaded constructors have the same name (name of the class) but the different number of
arguments. Depending upon the number and type of arguments passed, the corresponding
constructor is called.

Sample Code:

#include <iostream>
using namespace std;

class Person {
private:
int age;

public:
// 1. Constructor with no arguments
Person() {
age = 20;
}

// 2. Constructor with an argument


Person(int a) {
age = a;
}

int getAge() {
return age;
}
};

int main() {
Person person1, person2(45);

cout << "Person1 Age = " << person1.getAge() << endl;


cout << "Person2 Age = " << person2.getAge() << endl;

return 0;
}

Output:
C++ Copy Constructor:
A Copy constructor is an overloaded constructor used to declare and initialize an object from
another object.

Copy Constructor is of two types:


1. Default Copy constructor: The compiler defines the default copy constructor. If the user
defines no copy constructor, compiler supplies its constructor.
2. User Defined constructor: The programmer defines the user-defined constructor.

Syntax of User-defined Copy Constructor:


Class_name(const class_name &old_object);

Consider the following situation:

class A
{
A(A &x) // copy constructor.
{
// copyconstructor.
}
}

In the above case, copy constructor can be called in the following ways:
Let's see a simple example of the copy constructor.

#include <iostream>
using namespace std;
class A
{
public:
int x;
A(int a) // parameterized constructor.
{
x=a;
}
A(A &i) // copy constructor
{
x = i.x;
}
};
int main()
{
A a1(20); // Calling the parameterized constructor.
A a2(a1); // Calling the copy constructor.
cout<<a2.x;
return 0;
}

Output:

20

When Copy Constructor is called


Copy Constructor is called in the following scenarios:

o When we initialize the object with another existing object of the same class type. For
example, Student s1 = s2, where Student is the class.
o When the object of the same class type is passed by value as an argument.
o When the function returns the object of the same class type by value.

Two types of copies are produced by the constructor:


1. Shallow copy
2. Deep copy

Shallow Copy
o The default copy constructor can only produce the shallow copy.
o A Shallow copy is defined as the process of creating the copy of an object by copying data
of all the member variables as it is.

Let's understand this through a simple example:

#include <iostream>
using namespace std;
class Demo
{
int a;
int b;
int *p;
public:
Demo()
{
p=new int;
}
void setdata(int x,int y,int z)
{
a=x;
b=y;
*p=z;
}
void showdata()
{
cout << "value of a is : " <<a<< endl;
cout << "value of b is : " <<b<< endl;
cout << "value of *p is : " <<*p<< endl;
}
};
int main()
{
Demo d1;
d1.setdata(4,5,7);
Demo d2 = d1;
d2.showdata();
return 0;
}

Output:

In the above case, a programmer has not defined any constructor, therefore, the
statement Demo d2 = d1; calls the default constructor defined by the compiler.
The default constructor creates the exact copy or shallow copy of the existing object. Thus, the
pointer p of both the objects point to the same memory location.
Therefore, when the memory of a field is freed, the memory of another field is also
automatically freed as both the fields point to the same memory location.
This problem is solved by the user-defined constructor that creates the Deep copy.
Deep copy
Deep copy dynamically allocates the memory for the copy and then copies the actual value,
both the source and copy have distinct memory locations. In this way, both the source and copy
are distinct and will not share the same memory location. Deep copy requires us to write the
user-defined constructor.

Let's understand this through a simple example.

#include <iostream>
using namespace std;
class Demo
{
public:
int a;
int b;
int *p;

Demo()
{
p=new int;
}
Demo(Demo &d)
{
a = d.a;
b = d.b;
p = new int;
*p = *(d.p);
}
void setdata(int x,int y,int z)
{
a=x;
b=y;
*p=z;
}
void showdata()
{
cout << "value of a is : " <<a<< endl;
cout << "value of b is : " <<b<< endl;
cout << "value of *p is : " <<*p<< endl;
}
};
int main()
{
Demo d1;
d1.setdata(4,5,7);
Demo d2 = d1;
d2.showdata();
return 0;
}

Output:

In the above case, a programmer has defined its own constructor, therefore the statement Demo
d2 = d1; calls the copy constructor defined by the user. It creates the exact copy of the value
types data and the object pointed by the pointer p. Deep copy does not create the copy of a
reference type variable.

Differences b/w Copy constructor and Assignment operator (=)

Copy Constructor Assignment Operator

It is an overloaded constructor. It is a bitwise operator.


It initializes the new object with the existing It assigns the value of one object to another
object. object.

Syntax of copy constructor: Syntax of Assignment operator:


Class_name(const class_name &object_name) Class_name a,b;
{ b = a;
// body of the constructor.
}

The assignment operator is invoked when we


o The copy constructor is invoked when the
assign the existing object to a new object.
new object is initialized with the existing
object.
o The object is passed as an argument to the
function.
o It returns the object.

Both the existing object and new object shares Both the existing object and new object shares
the different memory locations. the same memory location.

If a programmer does not define the copy If we do not overload the "=" operator, the
constructor, the compiler will automatically bitwise copy will occur.
generate the implicit default copy constructor.

Destructors in C++:
What is destructor?
Destructor is a member function which destructs or deletes an object.

Syntax:
~constructor-name ();

When is destructor called?


A destructor function is called automatically when the object goes out of scope:
(1) the function ends
(2) the program ends

How destructors are different from a normal member function?


Destructors have same name as the class preceded by a tilde (~)
Destructors don’t take any argument and don’t return anything
Sample Code:

#include <iostream>
using namespace std;
class HelloWorld{
public:
//Constructor
HelloWorld(){
cout<<"Constructor is called"<<endl;
}
//Destructor
~HelloWorld(){
cout<<"Destructor is called"<<endl;
}
//Member function
void display(){
cout<<"Hello World!"<<endl;
}
};
int main(){
//Object created
HelloWorld obj;
//Member function called
obj.display();
return 0;
}

Output:
TASKS:
TASK 1:
Make a class named ‘Department’. While creating an object of the class, if nothing is
passed to it, then the message “I am not enrolled in any Department” should be
displayed. If some department name is passed to it, then in place of “I am not
enrolled in any Department” the name of the department should be displayed.

TASK 2:
Using constructor overloading create a C++ program that will calculate the area of.
1. Triangle
2. Square
3. Circle
4. Rectangle

Instructions:

 The Class name will be “Area” and overloaded Constructor name will be Area.
 For square it will take only one integer type parameter and will calculate the area using
the formula a*a.
 For rectangle it will take two integer type parameters L and B and will calculate its area.
 For circle the it will take two double type parameter pi and r will calculate the area of
circle within function with formula pi*r*r
 For triangle it will take three integer type parameter a, b and c and will calculate the are
using following formula.
area=sqrt(s*(s-a) *(s-b) *(s-c));
s=(a+b+c)/2;

You might also like