7 - Constructors and Other Tools Flashcards
What is a constructor?
A constructor is a member function of a class that is automatically called when an object of that class is declared.
How are constructors named?
They must have the same name as the class.
What do constructors return?
Nothing. They cannot return a value. Moreover, no type, not even void, can be given at the start of the function declaration or in the function header.
Constructors are placed in the public or private section of the class definition?
Public. If you were to make all your constructors private members, then you would not be able to declare any objects of that class type, which would make the class completely useless.
What is the scope resolution operator?
::
As in
DayOfYear :: DayOfYear (int monthValue, int dayValue)
There’s a pitfall associated with calling a default constructor. Which?
DayOf Year date3 ( ); IS WRONG
DayOfYear date3; IS RIGHT
It is tempting to think that empty parentheses should be used when declaring a variable for which you want the constructor with no arguments invoked, but the problem is that although you may mean it as a constructor invocation, the compiler sees it as a declaration of a function.
What are vectors?
Vectors can be thought of as arrays that can grow (and shrink) in length while your program is running.
Declare a variable v, for a vector with base type int.
vector v;
How do you add an element to a vector for the first time?
You use push_back:
vector sample;
sample.push_back(0.0).
This adds an element in the next available position.
How do you make sure you can use vectors in your program?
include
How do you know how many elements are in the vector?
v.size().
A common error associated with vector size is ..
Trying to set v[i] for i greater than or equal to v.size().
You may or may not get an error message, but your program will undoubtedly misbehave at some point.
What is the capacity of a vector?
Capacity is the number of elements for which it currently has memory allocated. This is larger than v.size ( ). The member function capacity ( ) can be used to find out the capacity of a vector.
How do you set the capacity of a vector, and why would you?
For performance purposes, you might want to make sure that the implementation of C++ doesn’t give your vector a capacity much larger than needed. This can be done using the member function reserve ( ) .
How do you cut away the last elements of a vector?
You can change the size of a vector using the member function resize.