C++ Flashcards
What does C++ add to C?
- Classes
- Exception handling
- Function & operator overloading
- Default values for parameters
- Pass by reference
What is ::?
Scope resolution operator
What removes the need for the scope resolution operator?
“using namespace std”
What does cout and cerr do?
cout: goes to stdout
cerr: goes to stderr
Why must two functions that are identical in all but input types be created?
They may result in different return types
In a .hpp class, what are the two key elements that define a class?
- Private class variables
- Public member function prototypes
What are the three access specifiers in a class?
- Private (default): can only be accessed within the class
- Public: can be accessed by any part of the program
- Protected: To do with inheritance
Where are functions for a class defined?
In a .cpp file with the same name as the .hpp file
How is a class used in a C++ file?
include <headerfilename.hpp></headerfilename.hpp>
What can be done if you have a class that can take a varying number of parameters?
Use overloading:
NewClass(int, int)
NewClass(int)
This is valid as there are a differing number of arguments
What values can be defaulted in a class function?
Only the trailing parameters
void NewClass::someFunction(int i, int j=0) (VALID)
void NewClass::someFunction(int i=1, int j=0) (VALID)
void NewClass::someFunction(int i=1, int j) (INVALID)
How has malloc been replaced in C++?
Instead of:
“int *p = (int )malloc(sizeof(int)25);
free(p);
It is now:
int *p = new int; // a single integer, uninitialised
int *p = new int(43); // a single integer, initialised to value 43
int *p = new int[25]; // an array of 25 integers
delete p; // free the single value p
delete[] p; // free the array p
What are constructors and destructors of a class?
They can be implicitly called when a object of the class type has been created or destroyed (i.e. when return 0 is stated). The constructor malloc memory to pointers and the destructor frees memory allocated to pointers.
What is a reference?
A reference is an alias for a variable
int num = 43;
int &ref = num;
ref = 43;
What is ‘this’?
‘this’ is a pointer to a current object and used to avoid ambiguities if you want to pass the object to a function or tor return a reference to the calling object
What is a copy constructor?
A member function that initialises an object using another object of the same class
MyClass (const MyClass &)
MyClass c, d;
MyClass e = c; // calls the copy constructor
d = e; // calls an assignment operator not the copy constructor
What is a static member variable?
- They are shared by all objects of the same class
- Can be accessed even if no objects exist