Sie sind auf Seite 1von 24

II.

Constructor and Destructor


PBO II. Constructor & Destructor

Constructor
 Is
used to initialize the data member of the class
 Analogy in variable:
 Define the variable and assign value to it
int Total ;
Total = 0;
 Define the variable and initialize it (the same as
using constructor)
int Total = 0;

2
PBO II. Constructor & Destructor

Creating Constructor

 Constructor can not have an output data type


 “Constructor name” has to be the same as the “class
name”
 To enable flexibility in creating object, It is possible
to create more than one constructor for one class
 Constructor will be called automatically when the
objects are created (users never call it directly)

3
PBO II. Constructor & Destructor

The Example of Constructor


class Tcar
{
private:
char _Name[50];
int _Gazoline_in_tank;
double _Price;
public:
// -- Constructor without argument -
Tcar();

// -- Constructor with argument -


Tcar(const char *Name, const int Gazoline_in_tank,
const double Price);
// and other member function below..
}; 4
PBO II. Constructor & Destructor

//------------- Constructor without argument -


Car()
{
_Gazoline_in_tank = 0;
_Price = 0;
strcpy(_Name, “Undefined car”);
}

//------------- Constructor with argument ------


Car (const char *Name, const int
Gazoline_in_tank, const double Price)
{
strcpy(_Name, Name);
_Gazoline_in_tank = Gazoline_in_tank;
_Price = Price;
}
5
PBO II. Constructor & Destructor

Or better implementation in .cpp


//------------- Constructor without argument ------
Car():_Gazoline_in_tank(0), _Price(0)
{
strcpy(_Name, “Undefined car”);
}

//------------- Constructor with argument ----------


Car(const char *Name, const int
Gazoline_in_tank, const double Price):
_Gazoline_in_tank(Gazoline_in_tank),
_Price (0)
{
strcpy(_Name, Name);
}
Note: It’s more common for the implementation of the constructor to be
put in .h file instead of in .cpp (The example in here just for clarity)6
PBO II. Constructor & Destructor

//Constructor will be called when objects created


{void main()

Tcar car1, car2(“Soluna”, 50,175000000);


Tcar car3;
// Constructor can’t be called after object
// created
// car3(“Amenity”, 45, 10000000); //--- Wrong
cout << car1.get_name() << “ “ <<
car1.get_gasoline_in_tank() << endl;

cout << car2.get_name() << “ “ <<


car2.get_gasoline_in_tank() << endl;
}
7
PBO II. Constructor & Destructor

Destructor
 Used to remove data in memory that has been
set using the keyword new. (For reference
variable)
 As constructor, the destructor can’t have an
output data type
 Destructor name must be the same as the class
name and must be preceded with “~” (tilde)
 Destructor will be called automatically when the
objects are out of scope

8
PBO II. Constructor & Destructor

class Tcar{
public:
char* _Name;
E int _Gazoline_in_tank;
X Tcar(){
A int length = strlen("Undefined Car");
_Name = new char[length + 1];
M strcpy(_Name, "Undefined Car");
P }
L //-Destructor-------------------------
~Tcar(){
E delete []_Name;
}
}; 9
PBO II. Constructor & Destructor
Memory Location for Object
Object created Memory when
Constructor is Memory when object destroyed
called object created without destructor
void main() Car2._GIT = 0 10 removed
{ Car2._Name = 100 12 removed
Tcar Car1;

:
}
100
“Undefined Car” “Undefined Car”
Object out of
scope in here,
destructor will
be called
automatically 10
PBO II. Constructor & Destructor
Memory Loc (cont.)
Memory when
object destroyed
with destructor Note: When the data are removed,
10 removed the content of the memory usually is
kept intact (still the same as before)
12 removed but the location actually is offered to
other data. Therefore reading the
content of this memory right away
after deleting, may give you the same
result (and give a false perception as if
100 your data still there). Worse case may
Removed !! happen if programmer altering the
content of the freed memory. This
action may crashing your computer
system (Hang).
11
PBO II. Constructor & Destructor

Just a little break


 Try in the main program - without setting the
length and width of the object generating from
your Tpersegi panjang class - displaying its area.
 Createsome constructor for your
Tpersegi_panjang class.
 Do the same as the first exercise, but now use
the Tpersegi_panjang class that already have
constructors.

12
PBO II. Constructor & Destructor

Copy Constructor
 What happen when you assign another object to a
new object such as:

Assign Car 2 from Car 1
Tcar Car2 = Car1;

 Or passing the object as an argument:
Car2.take_gazoline_from(Car1);

Passing Obj Car1 as an argument

When you don’t have pointer in your


Data Member and when you do 13
PBO II. Constructor & Destructor

Memory Location for Object


Memory allocation
after assignment
void main()
{ Car1._GIT = 0 10
Tcar Car1; Car1._Name = 100 12
Tcar Car2 = Car1; Car2._GIT = 0 14

}
Car2._Name = 100 16

:
100
Compiler will perform: “Undefined Car”
Car2._GIT = Car1._GIT
Car2._Name = Car1._Name

14
PBO II. Constructor & Destructor

What’s Wrong ? (this is Shallow Copy)


With this code
void main()
{
Tcar Car1;
Tcar Car2 = Car1;
Car1.set_name(“Sephia”);
Car1.set_gazoline_in_tank(50);
cout<<Car1.get_name()<<endl;
cout<<Car1.get_GIT ()<<endl;
cout<<Car2.get_name()<<endl;
cout<<Car2.get_GIT ()<<endl;
}

15
PBO II. Constructor & Destructor

Using Shallow copy


 Using shallow copy with above example, the name
and gasoline is not copied to Car2, because there is no
pointer variable in class Tcar
 But, if we place the code
 Tcar Car2 = Car1;
In the last line, the name and gasoline will be copied

16
PBO II. Constructor & Destructor

And This Code (destructor is implemented)


void main()
{
Tcar Car1 (“Sizuki Kerry”, 50);
int I_have_car = 2;
if (I_have_car > 1)
{
Tcar Car2 = Car1;
Car2.set_name(“Peugeot”);
Car2.set_gazoline_in_tank(40);
cout<<Car2.get_name()<<endl;
cout<<Car2.get_GIT ()<<endl;
}
Car1.set_name(“Balekno”);
} 17
PBO II. Constructor & Destructor

The expected memory loc.


Memory allocation
after assignment
Car1._GIT = 0 10
Car1._Name = 100 12
Car2._GIT = 0 14
Car2._Name = 150 16

:
100
“Undefined Car”

150
“Undefined Car”

18
PBO II. Constructor & Destructor

Characteristic of
Copy Constructor Copy Constructor
Tcar(const Tcar &temp_car){
_Gazoline_in_tank = temp_car._Gazoline_in_tank;

length = strlen (temp_car._Name);


_Name = new char[length + 1];
strcpy(_Name, temp_car._Name);
}

Allocating new memory location like this to place the different data,
often called DEEP COPY (as an opposed to SHALLOW COPY)
Deep copy will be automatically performed on :
Tcar Car2 = Car1; 19
PBO II. Constructor & Destructor

Shallow copy and deep copy


 Shallow copy
 The pointer will be simply copied as a value - so
both classes will point to the same original
memory, no new allocation takes place. Shallow
copy - this is what the language does by default.
 Deep copy
 If you need to allocate new memory and make a
copy of the data you have to do that yourself in the
copy constructor. Deep copy - you have to do this
yourself
20
PBO II. Constructor & Destructor

Conclusion
If you have a POINTER data member then
 Always create a destructor to delete the data
allocated using the keyword new
 Always create the copy constructor to perform deep
copy

21
PBO II. Constructor & Destructor
Exercise (Take home)

1. Buat class Segitiga (sama kaki), dengan ketentuan


 Variabel : double a, t

 Constructor : Segitiga (double init_a, init_t)

 //init adalah nilai awal utk a dan t

 Method : getA(), getT(), hitungLuas()

 Main :

 Input angka a dan t dgn metode cin atau scanf

 Buat sebuah objek segitiga1, daftarkan a dan t nya dengan

constructor, lalu cetak :


 Segitiga dengan a 15 dan t 10, luasnya 75

22
PBO II. Constructor & Destructor

2. Buat class Circle, dgn ketentuan


 Variabel : double r, luas, keliling. Char *color

 Color Digunakan utk menyimpan string, misal “red”

 Constructor : Circle(double init_r, char *color)


 Di constructor, langsung lakukan perhitungan luas dan keliling
 Method : getR(), getLuas(), getKeliling(), getColor()
 Main :
 Input angka r dengan metode cin atau scanf

 Buat objek circle1, panggil constructor, lalu cetak

 Circle berwarna red dengan r 14, luasnya 616, keliling 88

 Deconstructor : variable color


23
PBO II. Constructor & Destructor

3. Buat class Kucing, dgn ketentuan


 Variabel : double berat, Char *nama

 Constructor : Kucing () -> konstruktor kosong


 Nilai default dari kucing adalah :
 Berat 10, Nama “undefined cat”

 Method: setBerat, setNama, getBerat, getNama


 Main :
a) Buat objek kucing1, kucing2
b) Lakukan shallow copy dari kucing2 = kucing1
c) setBerat, setNama utk kucing1
d) Cetak berat, nama kucing1 dan kucing2
e) Coba ulangi poin a-d, poin b lakukan dengan deep copy
f) Simpulkan apa perbedaan shallow dan deep copy (catat di
comment program)
 Deconstructor : variable nama
24

Das könnte Ihnen auch gefallen