Lecture # 2
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 :
• 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);
Here is an example:
• 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);