Search

8.5 — Constructors

When all members of a class (or struct) are public, we can initialize the class (or struct) directly using an initialization list or uniform initialization (in C++11):

However, as soon as we make any member variables private, we’re no longer able to initialize classes in this way. It does make sense: if you can’t directly access a variable (because it’s private), you shouldn’t be able to directly initialize it.

So then how do we initialize a class with private member variables? The answer is through constructors.

Constructors

A constructor is a special kind of class member function that is automatically called when an object of that class is instantiated. Constructors are typically used to initialize member variables of the class to appropriate default or user-provided values, or to do any setup steps necessary for the class to be used (e.g. open a file or database).

Unlike normal member functions, constructors have specific rules for how they must be named:

  1. Constructors must have the same name as the class (with the same capitalization)
  2. Constructors have no return type (not even void)

Default constructors

A constructor that takes no parameters (or has parameters that all have default values) is called a default constructor. The default constructor is called if no user-provided initialization values are provided.

Here is an example of a class that has a default constructor:

This class was designed to hold a fractional value as an integer numerator and denominator. We have defined a default constructor named Fraction (the same as the class).

Because we’re instantiating an object of type Fraction with no arguments, the default constructor will be called immediately after memory is allocated for the object, and our object will be initialized.

This program produces the result:

0/1

Note that our numerator and denominator were initialized with the values we set in our default constructor! This is such a useful feature that almost every class includes a default constructor. Without a default constructor, the numerator and denominator would have garbage values until we explicitly assigned them reasonable values (remember: fundamental variables aren’t initialized by default).

Direct and uniform initialization using constructors with parameters

While the default constructor is great for ensuring our classes are initialized with reasonable default values, often times we want instances of our class to have specific values that we provide. Fortunately, constructors can also be declared with parameters. Here is an example of a constructor that takes two integer parameters that are used to initialize the numerator and denominator:

Note that we now have two constructors: a default constructor that will be called in the default case, and a second constructor that takes two parameters. These two constructors can coexist peacefully in the same class due to function overloading. In fact, you can define as many constructors as you want, so long as each has a unique signature (number and type of parameters).

So how do we use this constructor with parameters? It’s simple! We just use the direct initialization form of initialization:

This particular fraction will be initialized to the fraction 5/3!

In C++11, we can also use uniform initialization:

Note that we have given the second parameter of the constructor with parameters a default value, so the following is also legal:

Default values for constructors work exactly the same way as with any other function, so in the above case where we call six(6), the Fraction(int, int) function is called with the second parameter defaulted to value 1.

Rule: Use direct or uniform initialization with your classes

Copy initialization using equals with classes

Much like with fundamental variables, it’s also possible to initialize classes using copy initialization:

However, we recommend you avoid this form of initialization with classes, as it may be less efficient. Although direct initialization, uniform initialization, and copy initialization all work identically with fundamental types, copy-initialization does not work the same with classes (though the end-result is often the same). We’ll explore the differences in more detail in a future chapter.

Rule: Do not copy initialize your classes

Reducing your constructors

In the above two-constructor declaration of the Fraction class, the default constructor is actually somewhat redundant. We could simplify this class as follows:

Although this constructor is still a default constructor, it has now been defined in a way that it can accept one or two user-provided values as well.

When implementing your constructors, consider how you might keep the number of constructors down through smart defaulting of values.

A reminder about default parameters

The rules around defining and calling functions that have default parameters (described in lesson 7.7 -- Default parameters) apply to constructors too. To recap, when defining a function with default parameters, all default parameters must follow any non-default parameters.

This may produce unexpected results for classes that have multiple default parameters of different types. Consider:

With s4, we’ve attempted to construct a Something by providing only a double. This won’t compile, as the rules for how arguments match with default parameters won’t allow us to skip a non-rightmost parameter (in this case, the leftmost int parameter).

If we want to be able to construct a Something with only a double, we’ll need to add a second (non-default) constructor:

An implicitly generated default constructor

If your class has no other constructors, C++ will automatically generate a public default constructor for you. This is sometimes called an implicit constructor (or implicitly generated constructor).

Consider the following class:

This class has no constructor. Therefore, the compiler will generate a constructor that behaves identically to the following:

This particular implicit constructor allows us to create a Date object with no parameters, but doesn’t initialize any of the members (because all of the members are fundamental types, and those don’t get initialized upon creation).

Although you can’t see the implicitly generated constructor, you can prove it exists:

The above code compiles, because date object will use the implicit constructor (which is public).

If your class has any other constructors, the implicitly generated constructor will not be provided. For example:

Generally speaking, it’s a good idea to always provide at least one constructor in your class. This explicitly allows you to control how objects of your class are allowed to be created, and will prevent your class from potentially breaking later when you add other constructors.

Rule: Provide at least one constructor for your class, even if it’s an empty default constructor.

Classes containing classes

A class may contain other classes as member variables. By default, when the outer class is constructed, the member variables will have their default constructors called. This happens before the body of the constructor executes.

This can be demonstrated thusly:

This prints:

A
B

When variable b is constructed, the B() constructor is called. Before the body of the constructor executes, m_a is initialized, calling the class A default constructor. This prints “A”. Then control returns back to the B constructor, and the body of the B constructor executes.

This makes sense when you think about it, as the B() constructor may want to use variable m_a -- so m_a had better be initialized first!

In the next lesson, we’ll talk about how to initialize these class member variables.

Constructor notes

Many new programmers are confused about whether constructors create the objects or not. They do not (the code the compiler creates does that).

Constructors actually serve two purposes. The primary purpose is to initialize objects that have just been created. The secondary purpose is to determine whether creation of an object is allowed. That is, an object of a class can only be created if a matching constructor can be found. This means that a class without any public constructors can’t be created!

Although the main purpose of a constructor is to initialize an object, whether the constructor actually does an initialization is up to the programmer. It’s perfectly valid to have a constructor that does no initialization at all (the constructor still serves the purpose of allowing the object to be created, as per the above).

Finally, constructors are only intended to be used for initialization when the object is created. You should not try to call a constructor to re-initialize an existing object. While it may compile, the results will not be what you intended (instead, the compiler will create a temporary object and then discard it).

Quiz time

1) Write a class named Ball. Ball should have two private member variables with default values: m_color (“black”) and m_radius (10.0). Ball should provide constructors to set only m_color, set only m_radius, set both, or set neither value. For this quiz question, do not use default parameters for your constructors. Also write a function to print out the color and radius of the ball.

The following sample program should compile:

and produce the result:

color: black, radius: 10
color: blue, radius: 10
color: black, radius: 20
color: blue, radius: 20

Show Solution

1b) Update your answer to the previous question to use constructors with default parameters. Use as few constructors as possible.

Show Solution

2) What happens if you don’t declare a default constructor?

Show Solution

8.5a -- Constructor member initializer lists
Index
8.4 -- Access functions and encapsulation

298 comments to 8.5 — Constructors

  • McDidda

    somewhere I read that, our intention behind making a variable private was to make sure no function other than 'class member function ' can modify values of concerned variables. But consider the code below:

    thing is, now onwards any function can modify the class member m_x!. I was not expecting this fact to appear while I's reading the previous chapter. Can you explain?

    • Alex

      1) This is using the default copy constructor that is implicitly generated if you don't provide one. This is covered in chapter 9.
      2) This doesn't violate encapsulation / the point behind making variables private, as you're using the public interface of the class to change the value.
      3) If you don't want this behavior, you can disable the copy constructor using the delete keyword, also covered in chapter 9.

  • Jack

    hello chaps.
    default constructor:  why is it used instead of this?

    • Hi Jack!

      Last time this was brought up, Alex' reply was that this feature (Initializing members at their declaration) is newer than this lesson.
      Your version is preferred, because it initializes the members even when you add constructors that only partially initialize the members.

  • Stefan Gabriel

    Hello!
    I don't understand something. So c++ doesn't allow us to skip the leftmost parameter, so we have to make a special contructor for the second parameter, like in the Ball example. But what happens if we have more than two parameters and we wish to skip some of them? Will we have to make constructors for each individual parameter and then different combinations of them all?
    Thank you.

    • > Will we have to make constructors for each individual parameter and then different combinations of them all?
      Yep. C++ doesn't currently offer a way to explicitly use a default argument, so you're stuck with overloading functions for every combination you want to use.

  • Kio

    My 2cents,

    @nascardriver 🙂

  • erad

    Hi Alex,

    Thanks for this wonderful C++ site of yours! I need your take/insight on a segment of the code below, culled from a programming text I'm reading; the question the code attempts to answer is also shown.

    QUESTION: Write a program that takes a set of events, and determines the maximum number of events that take place concurrently.

    By the way, I fully understand the workings of the code but I do have a question about a recurring C++ programming feature that has nagged me for a while. It concerns the statements in Lines 20 and 21: I expect the items being emplaced into vector E to be objects; not types. I do not see any declared objects being inserted/emplaced here; rather, I see the type Endpoint being used. Why?

    It is objects (of types) that are initialized, not types! What is going on here?

    • Hi Erad!

      This code looks bad in my opinion, I advise you to read some other book or resource.

      Line 20 and 21 construct a new @Endpoint via uniform initialization (Lesson 2.1)

      @Endpoint should really be a class which would allow line 20 and 21 to omit the explicit constructor call and allow to parameters to be forwarded to the constructor like so

      • erad

        I strongly disagree with your opinion of the code, your counsel about the book (by the way, the three-man authorship consists of 2 Ph.D holding academics and a former Google exec) and your offered explanation.

        What makes the code look bad? It is structurally clean and performant in my view; and, if I am correct, it runs with a O(nlogn) time complexity.

        You wrote: "@Endpoint should really be a class ..." Why should it be if a simple struct can serve the same purpose? Aren't structs and classes pretty much the same except for the fact that the members of the former are, by default, public while those of the latter are private? And that structs usually do not contain member functions.

        Moreover, the manner in which vector E was declared in line 18 would preclude the 'emplacement' of data in E as you wrote.

        • > 2 Ph.D holding academics
          I've seen many Doctors who knew just what they needed to get their job done and were clueless about anything apart from that. This shouldn't be a reason to favor a book over another.

          > former Google exec
          Apparently not a coder, as the code doesn't follow Google's C++ style guide ( https://google.github.io/styleguide/cppguide.html ).

          > What makes the code look bad?
          * Each variable should be declared in it's own line
          * All variables should be initialized using uniform initialization
          * There's no way to tell the difference between a function and type based on the name
          * Function in a struct
          * using namespace
          * Poor variable names ("E", "A", "i", ...)
          * Inconsistent naming of variables (Underscore/Camel case)
          * Long lines

          > it runs with a O(nlogn) time complexity
          I didn't mean the algorithm.

          > Why should it be if a simple struct can serve the same purpose?
          Because it contains a function. Structs should only be used to hold data.

          > Aren't structs and classes pretty much the same except [...]
          Yes

          > Moreover, the manner in which vector E was declared in line 18 would preclude the 'emplacement' of data in E as you wrote.
          No. If @Endpoint has an appropriate constructor there is no problem.

          • erad

            I quite agree that academic degrees do not always (automatically) translate into skillful pedagogy. FYI however, the title of the book is "Elements of Programming Interviews" by Adnan Aziz et al (2014); you can check it out and see if the authors are lightweights and, also, if the soundness of their codes is impeachable. BTW, I wrongly referenced one of the authors as a 'former Google exec,' he is actually a Google software engineer.

            It seems like your dislike of the code stems from the theme of 'style,' and not 'functionality,' given the points you enumerated. That can be expected; people have different coding styles anyway.

            Going back to my original question, could it be that the arguments of the emplace_back functions in Lines 20 and 21 are 'anonymous objects'?

            • > could it be that the arguments of the emplace_back functions in Lines 20 and 21 are 'anonymous objects'?
              Yes they are. But the purpose of @emplace_back is to prevent the unnecessary copy/move of an anonymous object which occurs when using @push_back. @emplace_back accepts the arguments of the object's constructor and constructs the object directly inside the vector, omitting the copy/move.
              By passing anonymous objects you're loosing that advantage, because either the copy or move constructor of that object's type has to be called.
              Using a class+constructor rather than a struct allows proper use of @emplace_back.

              References
              std::vector::emplace_back - http://www.cplusplus.com/reference/vector/vector/emplace_back/
              std::vector::push_back - http://www.cplusplus.com/reference/vector/vector/push_back/

  • vbot

    Hi Alex,

    when I test the Fraction class from the constructor-example above:

    like this:

    Autocomplete in VS 2017 15.8.5 gives me following hints after the first brace is typed (starts with 2 of 3 as default selection):

    2 of 3 : Fraction(Fraction &&)
    3 of 3 : Fraction(const Fraction &)
    1 of 3 : Fraction(int numerator = 0, int denominator = 1)
                Default constructor

    Is this an IDE- / Autocomplete / IntelliSense issue or something else?
    What does (2 of 3) and (3 of 3) mean exactly (why proposed / visible)?

    Thanks!

    • vbot

      UPDATE:

      I've found several similar issues reported, it seems to be an IntelliSense/C++ problem.
      My workaround would be to simply press "arrow-up"-key after the opening brace, so the correct constructor-parameters-hints are shown (1 of 3).

      A little bit off-topic:
      This is really annoying, but VS seems to be the best C++ Editor arround when working with UE4 (which I intend to do).
      Would like to bet on CLion, but I believe Epic favours Visual Studio over CLion, because latest Versions of CLion seem to generally be kind of broken with latest Versions of UE4:
      https://blog.jetbrains.com/clion/2016/10/clion-and-ue4/

      but there are fixes:
      https://answers.unrealengine.com/questions/824973/clion-windows-ue4202-problem.html

      I'll give it a try.

      Thanks! 🙂

  • Kawless

    Why &color? Why not just color?

  • just a typo: trailing semicolon

  • i'am not sure but in "A reminder about default parameters" i think it also won't compile because of the uniform initialization (preventing the conversion error), because  of "7.6 — Function overloading" standard conversion if we wrote it with the direct initialization instead it would compile normally, but would convert the value of 2.4 to int and set to n which does not make sense

    • > but would convert the value of 2.4 to int and set to n which does not make sense
      That's why uniform initialization should be used. Calling @Something::Something with uniform initialization requires the caller to explicitly cast 2.4 to an int, making it obvious the the caller site what's happening. Using copy- or direct initialization could cause unexpected behavior, because the implicit cast most likely goes unnoticed.

  • Sam

    Typo: "Constructors actually serve two purpose." -> "Constructors actually serve two PURPOSES." By the way, thanks again for these lessons, I've learned so much in the last two weeks!

  • did this:

    which works as expected

  • Dear sir,

    Is this a bad practice, to initialize your variables in the definition within the class?

    My code -

  • matlag

    I have a question about constructors and initialization, so I'm going to ask this here, but I encountered the problem during the 9.3 quizz.

    I often try to put classes in separate files for all quizz, just so that I get a bit of practice doing so.
    My problem is about combining default values and initialization.

    in fraction.h

    in fraction.cpp

    The code in main.cpp

    will not compile, saying there is no Fraction::Fraction() constructor.

    I ended up creating a second explicit constructor, but that defeats the purpose of the default values.

    What is the correct approach to do this with a header file?

    • Hi Matlag!

      This isn't the cause for your problem. What is the error message you're getting?

      • matlag

        Ah, I had changed it but was able to repeat the issue.
        Let me post the whole thing.

        fraction.h

        fraction.cpp

        main.cpp

        Error message:

        • You code compiles and runs fine for me.
          Similar errors occur when fraction.cpp is not being compiled at all. Although this should cause more errors than the two you're seeing, make sure you're compiling fraction.cpp alongside main.cpp.
          Does your program compile without lines 30-38?

          • matlag

            Indeed!
            I'm using Qt Creator to handle the compilation.
            When calling g++ from the command line, it compiled.

            Thanks for the help! It's difficult to convince oneself to be right against the IDE...

            • matlag

              Answering myself: the error is fully on my side!
              I used to do a simple Ctrl+R in Qt Creator, which is the "Execute" command, and not a direct compiling command. It does compile if not done yet, but that's not its primary function.
              Asking for recompilation of everything worked.

  • Arumikaze

    Hello! I have a question about the use of const references in function parameters.

    In the answer provided, the string parameter is const and is using a reference:

    Why is string const, but not radius? Radius doesn't need to be changed so why isn't it also const? Why do we use a reference for string? I understand that the double can't use a reference because it needs a i-value. Will there be a noticeable performance difference if we didn't use references for strings in a large project?

    Thanks in advance!

    • Hi Arumikaze!

      > Why do we use a reference for string?
      @color is passed by reference, because strings have weird sizes which your computer isn't good at dealing with. A reference is always 4 or 8 bytes, both values which your computer likes. @radius doesn't need to be a reference, because doubles have a good size.

      > Why is string const, but not radius?
      @color is passed by reference, modifying @color in @Ball would modify the original variable. Additionally, if @color was a non-const reference, you wouldn't be able to pass an r-value.

      >Radius doesn't need to be changed so why isn't it also const?
      @radius doesn't need to be const, because modifying @radius inside @Ball doesn't touch the original. You could declare it const, to prevent yourself from accidentally modifying it, but this is rarely done.

      > Will there be a noticeable performance difference if we didn't use references for strings in a large project?
      Yes, copying data is an expensive operation.

      @Alex
      This is the third time this question has come up in the past week. It might be worth going into more detail or having some more examples about (const) reference parameters.

  • Lim Che Ling

    Hi, Alex,

    I tried to modify the code into this and found that the output has printed only 'B' (NOT A B)

    #include <iostream>
    #include <vector>

    class A
    {
    public:
        A() { std::cout << "A\n"; }
    };

    class B
    {
    private:
        std::vector<A> m_a; // B contains vector of A as a member variable
        A* m_b;
    public:
        B() { std::cout << "B\n"; }
    };

    int main()
    {
        B b;
        return 0;
    }

    This prints:
    B

    Does it mean if member variable of B is only pointer to A (A*) or vector<A>, the variable is not constructed? So how do I understand situation like when will constructor A be called or not? So the effect of having std::vector<A> m_a; and A* m_b; are to allow object B's member to store address that points to A later on?

    • nascardriver

      Hi Lim!

      @A's constructor only gets called when you construct an instance of @A. The pointer doesn't point anywhere and the vector is empty, so there's no instance of @A and thus no constructor called.

      > So the effect of having std::vector<A> m_a; and A* m_b; are to allow object B's member to store address that points to A later on?
      Correct

  • DecSco

    For the purpose of reusability, and because Color is kind of a class itself, I wanted to create a class "Color", that can print its color itself. Seemed more intuitive to me. Here's my code, which produces the correct results:

    However, I find the syntax "Color::Type::black" pretty cumbersome. Is there a better way of defining an enum (class) as part of a class?

    • nascardriver

      Hi DecSco!

      > Is there a better way of defining an enum (class) as part of a class?

      Or, since @Type is declared inside a class, you could use a regular enum. As long as it's inside a class it cannot pollute any code outside of it, you only have to watch out for collisions inside the class.

      • DecSco

        Ah! Then I'll just use a simple enum instead. Thank you! And thank your for your presence in the comment section in general! 🙂

      • DecSco

        I did exactly that, and suddenly, my Constructor doesn't work properly anymore. This code

        outputs

        So, that indicates that the enum "blue" gets promoted to a double (1.0), and the second constructor is used rather than the first, with "black" as the default value. That is surprising!

      • DecSco

        If I call it as

        it works correctly, but that's hardly better than

        and doesn't offer the same kind of security, as the responsibility is on the caller's side..

      • DecSco

        Ok, I think I found the correct way now. Rather logical, actually.
        Instead of a class as parameter for the constructor, and then calling it with an enum as argument (seems like some implicit conversion was going on), the constructors now look like this:

        Then everything works as intended.

  • Winchester

    In the second paragraph of "Constructor notes":
    "This means that a class without any public constructors can’t be created!"

    Doesn't the compiler will provide an implicit (and public) constructor? In what scenario does a class without any public constructors exist? Confused...

  • Peter Baum

    Why can't the code line

    be viewed as an error caused by not calling the constructor with the right arguments rather than because the compiler doesn't generate a default constructor?

    • nascardriver

      Hi Peter!

      That's a question for your compiler's maintainer. G++ suggest using another constructor:

      error: no matching function for call to ‘Date::Date()’
      note: candidate: ‘Date::Date(int)’
      note:   candidate expects 1 argument, 0 provided
      note: candidate: ‘constexpr Date::Date(const Date&)’
      note:   candidate expects 1 argument, 0 provided
      note: candidate: ‘constexpr Date::Date(Date&&)’
      note:   candidate expects 1 argument, 0 provided

  • Peter Baum

    Initially we are told in the Constructors section “Note that constructors are only intended to be used for initialization.” but then later in the section “An implicitly generated default constructor” we have the contradictory statement “This constructor allows us to create objects of the class, but does not do any initialization or assignment of values to the class members itself.”

    • Alex

      Not contradictory.

      Constructors are intended to be used for initialization of a class, and can only be invoked at initialization time. You can write a constructor and have it not do any initialization if you want.

      > This constructor allows us to create objects of the class, but does not do any initialization or assignment of values to the class members itself.

      I've amended this phrasing to the following:

      This particular implicit constructor allows us to create a Date object with no parameters, but doesn't initialize any of the members (because all of the members are fundamental types, and those don't get initialized upon creation).

      Is that clearer?

      • Peter Baum

        That is clearer.  Thanks Alex (I appreciate your taking the time to go through all these comments.)  I think what confuses me is that if the purpose of the constructor is to initialize and no initialization takes place, then why even bother having a constructor?  I think you mentioned in one of your comments that the constructor is also involved in checking for access rights, but I don't really understand fully what that means.

        • Alex

          > I think what confuses me is that if the purpose of the constructor is to initialize and no initialization takes place, then why even bother having a constructor? I think you mentioned in one of your comments that the constructor is also involved in checking for access rights, but I don't really understand fully what that means.

          With most classes, you can only create objects of the class if a particular public constructor exists that matches the user-provided arguments (or a default constructor exists if no arguments are provided). e.g.

          Now, if that constructor exists, it may or may not do any initialization (that's up to the programmer/class). But the mere presence or absence of the constructor determines whether or not the object can be constructed.

          I'll try to make this clearer in the lesson.

  • Peter Baum

    Are their any additional editing tags available besides the ones for code?

  • Peter Baum

    In section: A reminder about default parameters  -  the statement
    “To recap, when calling a function with default parameters, only the rightmost arguments may be defaulted.”
    is not clear and/or incorrect because of the ambiguity of the expression “rightmost arguments.”  In particular, the previous example showed that it is fine to have all the arguments defaulting:

    I think the intent is to say that all default parameters must follow any non-default parameters.  (Here “any” allows for the possibility of none.)

  • J Gahr

    Hey Alex, do you think it would be good to add another constructor to the solution for Quiz 1) that has this form:

    Otherwise, if the user did something like this:

    instead of this:

    the program wouldn't run. This would impact the solution to Quiz 1b too.

    • nascardriver

      Hi J!

      I don't think so. If you were to do this for all functions you'd have an exponential growth of function count plus what do you do with functions that take the same type of parameter multiple times?
      The compiler tells the coder what they've done wrong. One parameter order is enough.

  • Micah

    Typo:

    "This may product unexpected results for classes that have multiple default parameters of different types."

    should be

    "This may produce unexpected results for classes that have multiple default parameters of different types."

    "product" -> "produce"

    Thanks again for the tutorials

  • kdart

    If you have a class A, and the statement A* a = new A, why does that call an A constructor seeing as you haven't instantiated an A object, but only a pointer to an A object?

    • nascardriver

      Hi kdart!

      Creates an @A object (Therefore calls the constructor) and returns it's address.

      • kdart

        Ok.  Thank you.  I think maybe chapter 6.9 could be improved if you mentioned that new does indeed create a new object, rather than just set aside a chunk of memory the size of the object.

        • nascardriver

          'new' doesn't always create a new object. Michael Burr and Melebius gave a nice explanation over at stackoverflow https://stackoverflow.com/a/620402/9364954

  • Ran

    I just stuck with the question 8.3.1.b. Following is my code.

    I thought a default constructor like this could work for all the cases.

    However, the debug just pointed out that the following code skews up
    the program.

    The complier did not act as I expected, i.e. using std::string a =
    "Black" as default value, and use 20.0 as a input double b to
    initialize the m_radius.

    In stead, we have to write a special constructor:

    This, to me, is astonishing.

    • nascardriver

      Hi Ran!

      If you have a constructor like this

      You cannot just change the order or arguments when calling it. The first argument must be a string, the second must be a double. Having a default value for the first parameter allows you to construct a Ball without passing arguments and thus using the default values.
      There is no way to explicitly use a default value unfortunately. So you either have to pass a value manually or write another constructor without the parameter you want to skip.

    • Alex

      FWIW, I've updated the lesson to talk a bit more about this.

      It's interesting to consider why C++ doesn't support default non-rightmost arguments. I suspect that it introduces ambiguity in some cases.

  • Frieder

    You might want to change the default color in your quiz description from "Black" to "black". Elsewise the output wont match the expected result. 🙂

    This is a great site. Wished I would have found it earlier to finally settle down and learn C++.

    One thing to point out is that everybody should always compare their own solution against yours. Sometimes there are hidden gems in your solution that make it worth while to ponder over (avoiding overflows, ... ).

    BTW: I dont agree with your rule "avoid unsigned". I would rather make it mandatory to use specify both "unsigned" or "signed" (or use a specific type such as sint8_t or uint8_t) to indicate that it was given a second thought what type is being used. Simply using "int" is very often a clear indicator of "what the heck, I will think about it later" (and then you never do as we all know).

    Frieder

    • Alex

      Casing updated, thanks for pointing out the inconsistency.

      Using unsigned numbers is fine in specific cases, but those cases are pretty specific. The Google C++ style guide says, "You should not use the unsigned integer types such as uint32_t, unless there is a valid reason such as representing a bit pattern rather than a number, or you need defined overflow modulo 2^N. In particular, do not use unsigned types to say a number will never be negative. Instead, use assertions for this."

  • JMC

    iM LOSING MY MIND TO THIS COMPILATION ERROR 🙁

    Please help. Everytime i run it, it says that i have error C3867. But i dont understand why.

    I found the error, Peluca6.print needs to be Peluca6.print()

    Meh it hurts to lose so much time in little things like this. 🙁

    • nascardriver

      Hi JMC!

      From what I understand you solved your problem? That's good. Just a two notes:

      General: Program in english and use US ASCII if you expect anyone else to be able to understand and compile your code.
      Line 5: Don't use 'using namespace'

  • ram

    Thank you
    this is very helful

  • Michael

    Hi Alex,
    The compiler gave me a type mismatch when I was doing 1) with codes below:

    It marked blue("blue") as error and said "no instance of constructor "Ball::Ball" matches the argument list argument types are:(const char [5])

    Does that mean I have to define the parameter in a C-style string way? But I think std::string should have worked just fine.
    I'm using Visual Studio Community 2017 version 15.4.3
    Thanks!

    • Alex

      The problem here is that you've defined a bunch of constructors, but you didn't include them in the Ball class definition. The compiler should actually be complaining that the Ball constructors aren't members of the class.

      • Michael

        Thank you Alex. Solved it after moving constructors inside the class.

        I was using what VS autocomplete had given me when defining constructors.

        Every time I write a class it auto-completes into this:

        If I write my constructor in the very bottom MyClass function, the problem mentioned before will come up.
        Any idea?

        • Alex

          As long as the member functions defined outside the class (in this case, MyClass::MyClass and MyClass::~MyClass) have declarations inside the class (MyClass() and ~MyClass()), everything should work fine.

          I just realized I chat more about this in a future lesson in this chapter, but you haven't gotten there yet. Keep reading and the topic of how to define member functions outside the class will be covered.

Leave a Comment

Put all code inside code tags: [code]your code here[/code]