You are on page 1of 26

UNIVERSITY OF EMBU

DEPARTMENT OF MATHEMATICS, COMPUTING AND INFORMATION TECHNOLOGY

SIT 121: OBJECT ORIENTED PROGRAMMING

WRITTEN BY:
ACSC 328: Object Oriented Copyright © UNIVERSITY OF EMBU, JANUARY 2022
Dr. E.C TOO 1
Programming(C++) All Rights Reserved
Constructors and Destructors in C++
 Constructors are special class functions which performs 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.
 Destructor on the other hand is used to destroy the class object.
C++ Constructors

• To create a constructor, use the same name as the class, followed by


parentheses ():
• Example:
• class Display { // The class
public: // Access specifier
Display() { // Constructor
cout << "WELCOME TO OOP PROGRAMMING!";
}
};
int main() {
Display myObj; // Create an object of Display (this
will call the constructor)
return 0;
}
C++ Constructors
• Note: The constructor has the same name as the class, it is always
public, and it does not have any return value.
Constructor syntax
• Syntax

• class Area
• {
• public:
• int x;
• // constructor
• Area()
• {
• // object initialization
• }
• };
• Constructors can be defined either inside the class definition or outside
class definition using class name and scope resolution :: operator.
• class Area
•{
• public:
• int i;
• Area(); // constructor declared
• };
• // constructor definition
• Area::Area()
• {
• i = 1;
• }
Types of Constructors in C++

• Constructors are of three types:


Default Constructor
Parametrized Constructor
Copy Constructor
Default Constructors

• Default constructor is the constructor which doesn't take any


argument. It has no parameter.
• Syntax:
• class_name(parameter1, parameter2, ...)
•{
• // constructor Definition
•}
Example
• class Cube
•{
• public:
• int side;
• Cube()
• {
• side = 10;
• }
• };
• int main()
•{
• Cube c;
• cout << c.side;
•}
• A default constructor is so • class Cube
important for initialization of •{
object members, that even if • public:
• int side;
we do not define a • };
constructor explicitly, the
compiler will provide a • int main()
default constructor •{
implicitly. • Cube c;
• cout << c.side;
•}
Parameterized Constructors

• These are the constructors with parameter. • class Cube


• Using this Constructor you can provide • {
different values to data members of different • public:
objects, by passing the appropriate values as • int side;
argument. • Cube(int x)
• {
• side=x;
• }
• };
• int main()
• {
• Cube c1(10);
• Cube c2(20);
• Cube c3(30);
• cout << c1.side;
• cout << c2.side;
• cout << c3.side;
• }
Constructor Parameters
• Constructors can also take parameters (just like regular functions), which can be useful for setting initial values for attributes.
• 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;
}
Constructor Parameters
• 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):
Constructor Parameters
• 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;
}
Constructor Overloading in C++

 Just like other member functions, constructors can also be


overloaded.
 Infact when you have both default and parameterized constructors
defined in your class you are having Overloaded Constructors, one
with no parameter and other with parameter.
 You can have any number of Constructors in a class that differ in
parameter list.
• class Student
• {
• public:
• int rollno;
• string name;
• // first constructor
• Student(int x)
• {
• rollno = x;
• name = "None";
• }
• // second constructor
• Student(int x, string str)
• {
• rollno = x;
• name = str;
• }
• };
• int main()
• {
• // student A initialized with roll no 10 and name None
• Student A(10);

• // student B initialized with roll no 11 and name John
• Student B(11, "John");
• }
Destructor
• Destructor is a special class function which destroys the object as
soon as the scope of object ends.
• The destructor is called automatically by the compiler when the
object goes out of scope.
• The syntax for destructor is same as that for the constructor, the class
name is used for the name of destructor, with a tilde ~ sign as prefix
to it.
• class A • Destructors will never have any
• { arguments.
• public:
• // defining destructor for class
• ~A()
• {
• // statement
• }
• };
EXERCISE
• Write a program to print the area and perimeter of a triangle
having sides of 3, 4 and 5 units by creating a class named
'Triangle' with the constructor having the three sides as its
parameters.
• Write a C++ program that will implement a class containing the
dimensions of right-angled triangle (base and height) and a
parameterized constructor to initialize the dimensions as 12 and 5 cm
respectively. The program should then determine the length of the 3rd
side through use of a function and output it.
Access Specifiers

 Access specifiers define how the members (attributes and methods) of a class
can be accessed.
three access specifiers:
public - members are accessible from outside the class
private - members cannot be accessed (or viewed) from outside the class
protected - members cannot be accessed from outside the class, however,
they can be accessed in inherited classes.
• In the following example, we demonstrate the differences between public and private
members:
• class MyClass {
public: // Public access specifier
int x; // Public attribute
private: // Private access specifier
int y; // Private attribute
};
int main() {
MyClass myObj;
myObj.x = 25; // Allowed (public)
myObj.y = 50; // Not allowed (private)
return 0;
}
• Error: y is private
• Note: It is possible to access private members of a
class using a public method inside the same class. See
the next chapter (Encapsulation) on how to do this.
• Tip: It is considered good practice to declare your class
attributes as private (as often as you can).
• Note: By default, all members of a class are private if you don't
specify an access specifier:
• class MyClass {
int x; // Private attribute
int y; // Private attribute
};
EXERCISES
• Write a program to print the volume of a box by creating a class
named 'Volume' with an initialization list to initialize its length,
breadth and height. (just to make you familiar with initialization lists)
• Write a program that would print the information (name, year of
joining, salary, address) of three employees by creating a class named
'Employee'. The output should be as follows:
• Name Year of joining Address
• Robert 1994 64C- WallsStreat
• Sam 2000 68D- WallsStreat
• John 1999 26B- WallsStreat
Software Engineering Observation 19.1
• As a rule of thumb, data members should be declared private
• Member functions should be declared public.
• Except member functions that are accessed only by other member functions
of the class.

• Often useful to have get and set functions


• To access private members in controlled ways

ACSC 328: Object Oriented Introduction to Classes and Objects, Constructors and
25
Programming(C++) destructors
Summary
• Introduced class definitions and objects
• Public versus private access into class.
• Syntax for member functions
• Syntax data members
• Get and Set functions
• Constructors & Destructors
• Placing classes in separate files
• Separating interface from implementation

Introduction to Classes and Objects, Constructors and


26
destructors

You might also like