337 C++ (20-21) Flashcards
Will cover content from Week 6 to Week 8 Starts from basic I/O to classes
What do you need to include in order to use cin and cout?
#include <iostream>
What is the correct way to write cin and cout. (What is the extraction and insertion operator?)
Use cin and extraction operator, >>, to read one or more data Use cout and insertion operator << to display on the screen #include <iostream> int main() { // Example of using cin int number; std::cout << "Enter a number: "; std::cin >> number; std::cout << "You entered: " << number << std::endl; return 0; }
In order to use cin and cout in this format, what do we need to do? (Hint “using”)
Method 1:
using namespace std
Method 2:
using std::cout
using std::cin
What do the following math functions in <cmath> do? sqrt(x) pow(x, y) fabs(y) floor(x) ceil(x) exp(x) log(x)
square root
power
absolute
rounds down to the nearest int
rounds up to the nearest int
exponent
natural log
What is the basic format for a reference. Let’s say that the value we want to reference is
int ival = 1024;
int &refVal = ival;
Is this following code valid? Why or why not?
int &refval2;
int &refval2; // error, a reference must be initialized.
Let’s say that that in main we have
int main() {
int a = 45;
modify(a)
}
void modify(int & x){
x++;
}
What is x called? What is a called? (what’s their names?)
x is a reference and a is called a referent of x.
What are the two ways to type explicitly be using the type cast operator in C++?
Method 1: int x = 4; y = 7; double ratio = static_cast<double> x/y Method 2: int x = 4, y = 7; double ratio = double(x)/y;
Is the following a valid way to initialize a value?
int i(5);
Yes, it is equivalent to
int i = 5;
What are the two different ways to initialize a member
Member Initialization class_name::class_name(value_1, value_2){ member1 = value_1 member2 = value_2 } class_name::class_name(value_1, value_2): member1(value1), member2(value2){ }
What is a default constructor. What will happen if you don’t define one? In which cases will C make one for you?
Constructor that has no values passed through. Note that if you don’t define any constructors, C will make one for you. However if you define any constructor you will have to do it yourself.
What is the basic format for a getter function? Where do we place the constant?
double get_x()const;
char *get_label()const;
Since getter functions don’t need to change the values, we can add const to the end of the function declaration.
What is the correct way to use a pointer to an object?
Point c; Point *ptr; ptr = &c; cout << ptr ->get_x(); cout << (*ptr).get_x();
What is the following? Point::Point(double a, double b){ x = a; y=b;
This is a constructor
Do constructors have a return type? Can constructors be overloaded
No they don’t have a return type. Yes they can be overloaded
What is the :: operator? What does it do? Can several classes have member functions with the same name?
This is the scope resolution operator. It is used to associate a function to its corresponding class.
Yes several classes may have member functions with the same name.
What is the general format for the implementation of member functions?
return_type class_name::function_name(parameter_list){ }
Which of these is a default constructor, and which isn't? public: Point(); Point(double a, double b);
Point(); //default constructor Point(double a, double b); //non-default
What is the return type of a C++ class constructor
depends on the definition of the constructor.
True or False?
A class constructor can use the name of the class.
A class have more than one constructor.
Both statements are correct.
Let’s say that we have a getter function called get_x() in the class Point.
We then call Point a(6, 7);
How do we print the value of x?
cout << a.get_x() <<endl;
What is the difference between private and public members?
Private members can only be accessed by other members. They cannot be directly accessed using the dot operator.
Public members can be accessed from outside the class using the dot operator.
True or false, by default all class members are private.
True, all class members are private compared with struct data types where all members are public by default.
Where do we place function prototypes in classes?
We place it in public. Example:
class Point {
private:
double x;
double y;
public:
void set_x(double value);
void set_y(double value);
};
Is this class definition correct?
class Point {
private:
//some code
public:
//some code
}
No, we are missing the ; at the end. It should be }; at the end.
True or false, new creates a block of memory at run time.
True
Lets say that we have
int *array;
How would we allocate memory on the heap for an array with 5 elements? What will be the values stored inside?
array = new int[5];
It will initially be garbage inside.
Can we use delete if the space is not allocated or if the space has already been deallocated?
Do not use delete if the space is not allocated or if the space has already been deallocated.
How do we delete an array?
Use the delete operator to delete allocated memory by new.
delete [] array;
Only use [] when referring to an array of built in or user defined types.
Will dynamically allocated spaces be deallocated automatically?
No. Therefore a dynamically allocated space should be deallocated by the delete operator,
Given this following example, how would we deallocate x and y? Assume that Car is a class
Car *x;
Car *y;
x = new Car;
y = new Car[];
delete x; delete [] y;
What is a destructor?
Does a destructor have a return value?
Can a destructor receive a parameter?
Can a destructor be overloaded?
When is a destructor called?
A destructor is responsible for resetting the data member values or deallocation of memory.
A destructor doesn’t return a value and does not receive a parameter.
A destructor can NOT be overloaded
Destructor will be called automatically when an object goes out of scope. (It can also be called explicitly).
Let’s say that we have a class called Person. What would the destructor look like if it also has a member name = new char[strlen(n)+1] (essentially saying that name is a character string.
Person::~Person(){ delete [] name; name = NULL; }
What is a default constructor?
A default constructor is when you give the default values if the user provides a null argument.
Person::Person(const char *n = NULL, int a = 0{ age = a; name = new char [strlen(n)+1]; assert(n != 0); strcpy(name, n); }
What is the assert function?
The assert macro checks the given expression. If the expression is false (i.e., the condition is not met), the assert macro outputs a diagnostic message to the standard error stream (typically the console) and terminates the program.
In the following example,
const char *Student:: get_name() const
What does the first const do, and what does the second constant do?
The first const prevents the user from modifying the return value.
The second const prevents us from modifying any member variables inside the get_name function.
How can we use inline functions? What are inline functions?
What are the two methods for implementing inline functions?
If the function body is very short, the overhead of invoking a function call may be too high.
In these situations, we can use inline functions.
Method 1:
int get_value() {return value;}
Method 2:
inline void decrement (int n)
{
value -= n;
}
Can the compiler ignore your request for an inline function?
Will a change to an inline function require recompilation of all functions?
The compiler may ignore your request to inline a function
Any change to an inline function will require that all functions that call it be recompiled.
Can inline functions be recursive? Can inline functions contain an array?
No, inline functions cannot be recursive and cannot contain an array.
What are some advantages and disadvantages of inline functions?
Inline functions improve execution times but may increase program size.
How could we read characters (including whitespaces). How could we read strings?
We can use get() to read any character and getline() to read strings. char ch ch = cin.get(); string name; getline (cin, name); get example std::cin.get(ch); std::cout << "You entered: " << ch << std::endl; getline example std::getline(std::cin, line); std::cout << "You entered: " << line << std::endl;
How could we format output for fixed, scientific or setting precision to let’s say 2?
First we need to include
<iomanip>
cout<<setiosflags(ios::fixed);
cout<<setiosflags(ios::scientific);
Or another example is to do
cout<<setprecision(2); //sets the precision to 2.
Another option to set flag is:
cout<<fixed;
</iomanip>
How could we set the field size to display a value of x in a field of 10?
double x = 61110.56673
double x = 61110.56673 cout<<set.iosflags(ios::fixed)<<setprecision(2) <<"x=" <<setw(10)<<x; For this example assume _ is a whitespace. The output is x = 61110.56\_\_
Assuming that ^ represents a whitespace, what does the following output? int a = 3, b = 5; cout <<setw(7) << a << setw(7) << b;
^^^^^^3^^^^^^5
Each of the numbers are printed in a field of 7.
In the following code, will the 2nd cin work?
int i;
char ch
cout << "Please enter an integer "; cin >> i; cout << "Please enter a character "; cin >> ch; return 0;
No it will not read a character. This is because cin will consume just enough characters to do its job.
The solution:
char ch;
cin.clear();
do
{
ch = cin.get(); //reads a character
} while (ch != ‘\n’ && ch!= EOF);
Let’s say that we have a constructor Person
Person::Person(const char *n, int a)
We wish the save n into a member called name. How would we do that assignment. Let’s also say that we want to do this dynamically on the heap.
name = new char [strlen(n)+1];
Note that we add 1 since we need to add the \0.
Which of the following is a call to the constructor?
MyString s1(“World”);
MyString s2 = s1;
MyString s1(“World”); //this is a call to the constructor.
MyString s2 = s1; This is not a call. This is initialization.
What are the issues with something like MyString s2 = s1;
S2 is not a real copy of s1. They point to the same place on the heap.
The destructor of MyString will be called twice when s1 and s2 go out of scope. The destructor will attempt to deallocate the storage twice leading to a possible segmentation fault.
How would we define a copy constructor. Assume the class is called MyString and we want to copy over strings.
MyString::MyString(const MyString &s): lengthM(s.lengthM)
{
storageM = new char[lengthM+1];
assert(storageM != 0);
strcpy(storageM, s.storageM);
}
How do we format a strcpy?
char *strcpy(char *dest, const char *src);
’’’
Is the following inline function correct?
int get_value() {return_value};
‘’’
No. The semi colon is in the wrong place. It should be
int get_value() {return value;}