Object Oriented Programming Lab 4
Object Oriented Programming Lab 4
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;
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;
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;
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:
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;
}
int getAge() {
return age;
}
};
int main() {
Person person1, person2(45);
return 0;
}
Output:
C++ Copy Constructor:
A Copy constructor is an overloaded constructor used to declare and initialize an object from
another object.
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
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.
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.
#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.
#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.
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 ();
#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;