0% found this document useful (0 votes)
10 views21 pages

Lecture # 2

The document provides an overview of constructors in C++, explaining their purpose, characteristics, and usage, including default constructors and passing arguments. It also covers destructors, overloading constructors, and creating arrays of class objects. Examples illustrate how to define and initialize objects using constructors, including those with default arguments and how to access members of objects in an array.

Uploaded by

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

Lecture # 2

The document provides an overview of constructors in C++, explaining their purpose, characteristics, and usage, including default constructors and passing arguments. It also covers destructors, overloading constructors, and creating arrays of class objects. Examples illustrate how to define and initialize objects using constructors, including those with default arguments and how to access members of objects in an array.

Uploaded by

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

Lecture # 2

constructor :
• A constructor is a member function that is automatically called when
a class object is created.
• A constructor has the same name as the class.
• A constructor has no return type—not even void. This is because
constructors are not executed by explicit function calls and cannot
return a value.
• useful for initializing member variables .
Example:
class Demo
{
public:
Demo(); // Constructor
};

Demo::Demo()
{
cout << "Welcome to the constructor!\n";

}
int main()
{
Demo demoObject; // Define a Demo object;
cout << "This program demonstrates an object\n";
cout << "with a constructor.\n";
return 0;
}

Program Output :
Welcome to the constructor!
This program demonstrates an object
with a constructor.
The Default Constructor :

• If you write a class with no constructor whatsoever, when the class is


compiled C++ will automatically write a default constructor that does
nothing.
• For example, the first version of the Rectangle class had no
constructor; so, when the class was compiled C++ generated the
following constructor:
Rectangle::Rectangle()
{
}

*A default constructor takes no arguments.


Passing Arguments to Constructors:
• A constructor can have parameters and can accept arguments when
an object is created.

• Constructors may accept arguments in the same way as other


functions.

• When a class has a constructor that accepts arguments, you can pass
initialization values to the constructor when you create an object.
Example:
class Rectangle {

private:
double width;
double length;
public:
Rectangle(double, double); // Constructor
void setWidth(double);
void setLength(double);

double getWidth() const


{ return width;
}
double getLength() const
{ return length;
}
double getArea() const
{ return width * length; } };
Constructor definition:
Rectangle::Rectangle(double w, double len)
{
width = w;
length = len;
}
Object Definition:
The constructor is automatically called when a Rectangle object is
created, the arguments are passed to the constructor as part of
the object definition.

Here is an example:

Rectangle box(10.0, 12.0);


• This statement defines box as an instance of the Rectangle class.
• The constructor is called with the value 10.0 passed into the w
parameter and 12.0 passed into the len parameter .

Rectangle box(10.0, 12.0); width:10.0


length:12.0
The box object is initialized
with width set to 10.0 and length set to 12.0
Using Default Arguments with Constructors :
• Like other functions, constructors may have default arguments.
• default arguments are passed to parameters automatically if no
argument is provided in the function call.
• The default value is listed in the parameter list of the function’s
declaration or the function header.
class Sale {
private:
double itemCost; // Cost of the item
double taxRate; // Sales tax rate
public:
Sale(double cost, double rate = 0.05)
{
itemCost = cost;
taxRate = rate;
}
double getItemCost() const {
return itemCost; }
double getTaxRate() const {
return taxRate; }
double getTax() const {
return (itemCost * taxRate); }
double getTotal() const {
return (itemCost + getTax() );
}
Using Default Arguments with Constructors :
• If a constructor has default arguments for all its parameters, it can be called
with no explicit arguments. It then becomes the default constructor.
Example:
Sale(double cost = 0.0, double rate = 0.05)
{
itemCost = cost;
taxRate = rate; }
the constructor can be called with no arguments:
Sale itemSale;

This statement defines a Sale object. No arguments were passed to the


constructor, so the default arguments for both parameters are used
Destructor:

• A destructor is a member function that is automatically called when an


object is destroyed.
• Destructors are member functions with the same name as the class,
preceded by a tilde character (~).
• For example, the destructor for the Rectangle class would be named
~Rectangle.
• Destructors perform shutdown procedures when the object goes out of
existence.
• a common use of destructors is to free memory that was dynamically
allocated by the class object.
Overloading constructors
• A class can have more than one constructor.
• Constructors with the same name may exist in a C++
program, as long as their parameter lists are different.
class InventoryItem
// Constructor #2
{
private: InventoryItem(string desc)
string description; { description = desc;
double cost; cost = 0.0;
units = 0; }
int units;
public: // Constructor #3
// Constructor #1
InventoryItem() InventoryItem(string desc, double c, int u)
{
{ description = "";
description = desc;
cost = 0.0; cost = c;
units = 0; } units = u; }
Arrays of Class Objects:
As with any other data type in C++, you can define arrays of class objects.
Example:
An array of InventoryItem objects could be created to represent a business
inventory records.
const int ARRAY_SIZE = 40;
InventoryItem inventory[ARRAY_SIZE];

This statement defines an array of 40 InventoryItem objects. The name of the


array is inventory, and the default constructor is called for each object in the
array.
Arrays of Class Objects:

constructor that requires arguments:

InventoryItem inventory[] = {"Hammer", "Wrench", "Pliers"};

• This statement defines an array of three objects and calls that constructor for
each object.
• The constructor for inventory[0] is called with “Hammer” as its argument, the
constructor for inventory[1] is called with “Wrench” as its argument, and the
constructor for inventory[2] is called with “Pliers” as its argument.
• If a constructor requires more than one argument, the initializer must take the
form of a function call.
• For example,
InventoryItem inventory[] = {
InventoryItem("Hammer", 6.95, 12),
InventoryItem("Wrench", 8.75, 20),
InventoryItem("Pliers", 3.75, 10) };

• It isn’t necessary to call the same constructor for each object in an array.
• For example, look at the following statement.
InventoryItem inventory[] = { "Hammer",
InventoryItem("Wrench", 8.75, 20),
"Pliers" };
The default constructor is called for the third object.
const int SIZE = 3;
InventoryItem inventory [SIZE] = { "Hammer",
InventoryItem("Wrench", 8.75, 20) };
Accessing Members of Objects in an Array
• Objects in an array are accessed with subscripts, just like any other
data type in an array.
• For example, to call the setUnits member function of inventory[2],
the following statement could be used:

inventory[2].setUnits(30);

 Ref: See complete Example pg.no 762.

You might also like