Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

C++ Constructors #216

Open
Qingquan-Li opened this issue Jul 15, 2022 · 0 comments
Open

C++ Constructors #216

Qingquan-Li opened this issue Jul 15, 2022 · 0 comments
Labels

Comments

@Qingquan-Li
Copy link
Owner

Qingquan-Li commented Jul 15, 2022

1. What's Constructors

Concept: A constructor is a member function that is automatically called when a class object is created.

A constructor is a member function that has the same name as the class. It is automatically called when the object is created in memory, or instantiated.

It is helpful to think of constructors as initialization routines. They are very useful for initializing member variables or performing other setup operations.

Example:

// This program demonstrates a constructor.

#include <iostream>
using namespace std;

// Demo class declaration.

class Demo {
public:
    Demo(); // Constructor
};

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

int main() {
    // Define a Demo object
    // When an instance of this class is defined,
    // the function Demo is automatically called.
    Demo demo_object;

    return 0;
}

Output:

Welcome to the constructor!

Notice the constructor's function header looks different than that of a regular member function. There is no return type—not even void. This is because constructors are not executed by explicit function calls and cannot return a value.

The function header of a constructor's external definition takes the following form:

ClassName::ClassName(ParameterList)

2. The default Constructor

A default constructor is a constructor that takes no arguments.

Like regular functions, constructors may accept arguments, have default arguments, be declared inline, and be overloaded.

If you write a class with no constructor whatsoever, when the class is compiled, C++ will automatically write a default constructor that does nothing.


Classes with No Default Constructor

When all of a class's constructors require arguments, then the class does not have a default constructor.
In such case, you must pass the required arguments to the constructor when creating an object. Otherwise, a compiler error will result.


Only one default constructor

When an object is defined without an argument list for its constructor, the compiler automatically calls the default constructor. For this reason, a class may have only one detault constructor.

If there were more than one constructor that could be called without an argument, the compiler would not know which one to call by default.

Remember, a constructor whose parameters all have a default argument is considered a default constructor. It would be an error to create a constructor that accepts no parameters along with another constructor that has default arguments for all its parameters.
In such case, the compiler would not be able to resolve which constructor to execute.


3. Passing Arguments to Constructors

Concept: A constructor can have parameters and can accept arguments when an object is created.

Constructors may accept aeguments 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:
    	Rectangel(double, double); // Constructor
    	...
};

// The constructor accepts arguments for width and length.
Rectangle::Rectangle(double w, double len) {
    width = w;
    length = len;
}

// Create a Rectangle object, pass initialization values to the constructor
Rectangle box(10.0, 20.0);

The constructor accepts two arguments, which are passed into the w and len parameters. The parameters are assigned to the width and length member variables.

Because the constructor is automatically called when a Rectangle object is created, the arguments are passed to the constructor as part of the object definition:

Rectangle box(10.0, 20.0);

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

As a result, the object's width member varivale will be assigned 10.0 and the length member variable will be assigned 20.0.


4. Overloading Constructors

Concept: A class can have more than one constructor.

As long as each constructor takes a different list of parameters, the compiler can tell them apart.
For example, the string class has several overloaded constructors. The following statement creates a string object with no arguments passed to the constructor:

string str;

This executes the string class's default constructor, which stores an empty string in the
object.

Another way to create a string object is to pass a string literal as an argument to
the constructor, as shown here:

string str("Hello");

This executes an overloaded constructor, which stores the string "Hello" in the object.

Example

Let's look at an example of how you can create overloaded constructors. The InventoryItem class holds the following data about an item that is stored in inventory:

  • Item's description (a string object)
  • Item's cost (a double)
  • Number of units in inventory (an int)

To simplify the code, all the member function are written inline.

#include <iostream>
#include <string>
#include <iomanip>

using namespace std;

class InventoryItem {
private:
    string description; // The item description
    double cost;        // The item cost
    int units;          // Number of units on hand
public:
    // Constructor #1 (default constructor, takes no arguments)
    InventoryItem() {
        // Initialize description, cost, and units.
        description = "";
        cost = 0.0;
        units = 0;
    }

    // Constructor #2
    InventoryItem(string desc) {
        // Assign the value to description.
        // This constructor accepts only one argument, the item description.
        description = desc;
        // Initialize cost and units.
        cost = 0.0;
        units = 0;
    }

    // Constructor #3
    InventoryItem(string desc, double c, int u) {
        // Assign the value to description, cost, and units.
        // This constructor accepts arguments for the description, cost, and units.
        description = desc;
        cost = c;
        units = u;
    }

    // Mutator functions
    void setDescription(string d) {
        description = d;
    }
    void setCost(double c) {
        cost = c;
    }
    void setUnits(int u) {
        units = u;
    }

    // Accessor functions
    string getDescription() const {
        return description;
    }
    double getCost() const {
        return cost;
    }
    int getUnits() const {
        return units;
    }
};

int main() {
    // Create an InventoryItem object with constructor #1.
    InventoryItem item1;
    item1.setDescription("Hammer");
    item1.setCost(6.95);
    item1.setUnits(12);

    // Create an InventoryItem object with constructor #2.
    InventoryItem item2("Pliers");

    // Create an InventoryItem object with constructor #3.
    InventoryItem item3("Wrench", 8.75, 20);

    cout << setprecision(2) << fixed << showpoint;

    // Display the data for item 1.
    cout << "Description: " << item1.getDescription() << endl;
    cout << "Cost: $" << item1.getCost() << endl;
    cout << "Units on Hand: " << item1.getUnits() << endl << endl;

    // Display the data for item 2.
    cout << "Description: " << item2.getDescription() << endl;
    cout << "Cost: $" << item2.getCost() << endl;
    cout << "Units on Hand: " << item2.getUnits() << endl << endl;

    // Display the data for item 3.
    cout << "Description: " << item3.getDescription() << endl;
    cout << "Cost: $" << item3.getCost() << endl;
    cout << "Units on Hand: " << item3.getUnits() << endl << endl;

    return 0;
}

Output:

Description: Hammer
Cost: $6.95
Units on Hand: 12

Description: Pliers
Cost: $0.00
Units on Hand: 0

Description: Wrench
Cost: $8.75
Units on Hand: 20

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant