Loading...

C++ Constructors

The members page left one line on the screen in box.cpp: pine, after t.word = "pine"; and t.show(). This page stays in the same file and the same Classes module. The type name Tag, the member word, and show stay. The new work fills word when the object is built, so the separate assignment line goes away. The screen still shows one line: pine.
A constructor is a special member function whose name matches the class name. It runs when you create an object. On this page you write Tag(std::string w) and inside it word = w;. Then main builds with Tag t("pine"); instead of Tag t; plus t.word = "pine";. The Classes cast keeps Tag and box.cpp. The value pine is still the member on the object; the constructor is the tool that places it there at creation time. Reading the creation line is reading both the type and the first values the object should hold.
Programs use constructors so a new object starts with the data it needs. You do not leave word empty and fill it later on this page. Creating two objects with two different constructor arguments can print two different words, but this page builds one object so the screen stays one clear line. The next page names a tool that talks about the current object from inside a member. Here the point is only the constructor call with parentheses after the type when you declare the variable. The build command stays familiar: one source file box.cpp, one output name box, one run that prints pine.

Above main, keep class Tag with std::string word; and show that prints word. Add the constructor under public:: Tag(std::string w) with braces, and inside set word = w;. Keep the includes for iostream and string. There is still no second main inside Tag. The constructor has no return type line. Its name is Tag, matching the class.
Inside main, replace the old pair of lines with one creation: Tag t("pine");, then t.show();, then return 0;. The parentheses pass pine into the constructor parameter w. The constructor stores it in word. The call to show prints that member. You are not writing t.word = "pine"; on this page.
Walk the run. The program starts at main. Tag t("pine"); builds one object and runs the constructor, which sets word to pine. t.show(); prints pine. Then show finishes, main returns, and the program ends. There is one line on the screen. It is still pine. The assignment after creation is gone from the checked file. By the time show runs, word already holds pine because the constructor finished first.

If you write Tag t; with no argument while the only constructor needs a string, the build fails. That failed experiment stays in the prose. The checked file always passes "pine" in the creation line.
If you keep both Tag t("pine"); and t.word = "cone"; before show, the screen would show cone, because the later assignment overwrites the constructor fill. The checked file does not overwrite. It lets the constructor own the first fill.
A common mistake is to give the constructor a return type such as void Tag(...), which the build rejects. Another common mistake is to name the constructor something other than Tag. A third mistake is to leave t.word = "pine"; and also use a constructor, so two fills fight. A fourth mistake is to call the constructor like a normal function from main without creating an object. A fifth mistake is to forget the parameter and still write Tag t("pine");, so the build fails about no matching constructor.
This page stops before the next tool, where a member refers to the current object with a special name. The next page names that tool once at the end. The constructor you have just written only shows how members get their first values at build time.

Open box.cpp. Keep the includes, word, and show. Add Tag(std::string w) that sets word = w;. In main, write Tag t("pine"); and remove the separate t.word = "pine"; line, then call t.show();. The file name on disk stays box.cpp. The checked file is below, and the new lines are the constructor and the creation call with "pine".

box.cpp builds Tag t with a constructor that sets word

cpp
#include <iostream>
#include <string>

class Tag
{
public:
    std::string word;
    Tag(std::string w)
    {
        word = w;
    }
    void show()
    {
        std::cout << word << std::endl;
    }
};

int main()
{
    Tag t("pine");
    t.show();
    return 0;
}

Rebuild with g++ -std=c++17 box.cpp -o box, then run ./box. If g++ is missing and clang++ is the compiler you installed, swap only the tool name: clang++ -std=c++17 box.cpp -o box. The screen shows one line: pine.
Check that line first. The constructor stored pine, and t.show printed it. The table gives each row its piece, so compare your run with it line by line. If the screen is blank, show is missing or word was never set in the constructor. If the build fails about no matching constructor, the creation line and the constructor parameters do not match. If the build fails about a return type on Tag, remove that return type from the constructor header.

📊 The constructor and what it shows

Piece What the screen shows
First pine, because Tag t("pine") fills word in the constructor
Last pine, because the program prints one line and stops
Rule a constructor runs when the object is built and can set members
Screen pine

Try one change at a time. Change Tag t("pine"); to Tag t("cone");, leave the constructor body as it is, and rebuild. The screen shows cone instead of pine, because only the argument at creation changed. Put "pine" back. Next, after t.show();, add Tag u("cone"); and u.show();, leave the first object as it is, and rebuild. The screen shows pine, then cone, because each constructor call fills its own object. Remove the second object before you leave so the file returns to the checked one-line shape. Each experiment changes one thing, so the screen shows exactly which creation argument was stored. Undo each change before the next one starts, so the file always returns to the checked version.
This page ends the constructors tool and stops before the next one. The next page is this, which names the current object from inside a member. The constructor you have just written only shows filling word at build time. You leave with one line on the screen: pine. Count the lines before you leave. There is exactly one printed line, and it is pine.

🧠 Test Your Knowledge

Ready to Start

Test Your Knowledge

Challenge yourself with this interactive quiz and see how well you understand the topic

❓
4
Questions
🎯
70%
To Pass
♾️
∞
Time
🔄
∞
Attempts

📝 Instructions

  • Read each question carefully
  • Select the best answer for each question
  • You can retake the quiz as many times as you want
  • Your progress will be shown at the top