CS3307 Final
Preproceessor Directives: include guards
#ifndef MYHEADER_H #define MYHEADER_H ... #endif
C++ also allows parameters to be passed by reference by designating them with an
& in the function declaration. The variable in the function definition is not a local variable in this case, but rather an alias to the variable outside of the function and passed into it as a parameter As a result, changes in value within the function propagate outside the function as well Only use pass by reference when this behaviour is necessary, otherwise things can get rather confusing!
Insertion operator
(<<) does output
Extraction operator
(>>) does input
Limitations of Extraction: If erroneous data is entered
(a letter instead of a number, for example), the extraction operator isn't equipped to handle it; instead of reading the data, it puts a premature end to the extraction
Why C++?
-> C++ is the fourth most popular programming language according to the latest TIOBE index for 2019, behind Java, C, and Python -> It is often praised for generally doing a good job of merging the benefits of object-orientation with the power and speed of C -> Its template library provides a decent collection of starting points, and add-on packages like Boost take things even further -> Mastering C++ will also make you a better programmer at C, Java, C# and many other languages - approaching things the other way is significantly more challenging
Why not C++?
-> C++ lacks garbage collection and forces users to manage memory on their own (though some people see this as a plus) -> C++ lacks some high level language features like reflection (Reflection: program asking questions (eg. Checking objects type)) -> Templates, while beneficial, are still harder to use and more error prone than they should be in practice -> Some recent developments in the language are perceived as feature creep and unnecessary
A couple of things to keep in mind about friends: 2
-> Friendship is not reciprocal; just because X is a friend of Y, that does not mean that Y is a friend of X, unless it is explicitly declared -> Friendship is not transitive; a friend of a friend is not considered a friend, again unless explicitly declared
Copy constructor can be used to 3
-> Initialize one object from another of the same type -> Copy an object to pass it as an argument to a function ->Copy an object to return it from a function
3 ways function can exit
-> It executes a return statement, providing a return value of the appropriate type (or not providing anything in the case of a void function) -> Reaching the end of the function body, which is only allowed in void functions or main(), in which case this indicates successful completion -> Calling a system function that does not return (like exit())
Benefits of object-oriented programming: Modularization
-> Refers to the design approach where a software application is implemented as a collection of independent units (subsystems) that communicate by exchanging only the absolutely necessary information (data) that is required to perform an operation -> In other words, they have low coupling -> Furthermore, each unit (subsystem) performs a specific operation or a collection of very closely related operations -> In other words, they have high cohesion -> Usually, a collection of related classes constitutes a subsystem
2 problems with static members
-> Static member variables are more-or-less the same as having global variables, albeit potentially with some access restrictions -> Because static member variables are essentially shared between all objects of a class, they represent a threat to thread-safeness and access to them needs to be regulated like other globally shared data
2 ways C++ arrays different than C arrays
-> You can use new and delete to manage dynamically allocated arrays instead of only malloc and free -> Newer C++ standards also allow you to have initializer lists to dynamically allocate an array and initialize its contents in one step int foo1[5]; or int foo2[5] = {1, 2, 3, 4, 5};
Errno if there is no error will be
0
Entire programs in C++ can be written using only regular functions not defined in any class
; in other words, classes are not mandatory
How to build in multiple steps in command line
> g++ -c HelloWorld.cpp > g++ HelloWorld.o -o HelloWorld > ./HelloWorld
how to build in one step in command line
> g++ HelloWorld.cpp -o HelloWorld > ./HelloWorld
When is destructor called
A destructor is automatically called whenever an object of this class is being destroyed (when delete is used, or when a function returns and it has objects in its stack frame)
Function Definition
A function definition is a function declaration alongside a presentation of the body of the function
Friend Function
A non-member function can access the private and protected members of a class if it is declared a friend of that class
using namespace std;
Allows you to use cout and end1 without std::
Static member definition
By declaring a class member as static, it is possible to have that member belong to the class itself, as opposed to individual members of the class. Such static members, in a way, are essentially shared among all objects of the class. Static members can also be accessed without requiring the instantiation of an object in advance.
At the core of the STL(Standard template library) are: 3
Containers, algorithms, and iterators
Object orientation is not the solution to every programming need
Data base applications -> SQL, 4GLs Embedded systems -> Assembly, .....
The virtual keyword enabled dynamic dispatching
In this case, the compiler does not know which method to invoke at compile time and instead the program needs to determine this at run-time as a derived class might override the method
Namespaces
Namespaces provide a method for explicitly defining scope to the identifiers within it (e.g. types, functions, variables, etc.)
what does . mean in Tr2.base
Operation is working with object on stack (struct)
Function in C++ have thing diff from functions in C
Optionally, one or more modifiers designating special behaviour of the function or modifying how the compiler treats or compiles it (this is where things can get ugly and deviate from C ...) Modifer: how function is called, how its executed, allows you to have optimization.
Function Parameter: What about our swap function though? Recall that it exchanges the values in the two variables pointed to by its parameters! Does this not break the pass by value rules?
Passed pointers to stack frame but they pointed to the heap and manipulated the variables which is why it is fine.
Performance of Template
Performance hit in the way that the template is executed.
Polymorphism
Polymorphism means "many forms" In C++, we are usually referring to sub-type polymorphism, in which we can make use of derived classes through base class pointers and references
Preprocessor directives
Preprocessor directives begin with a # and generally take an entire single line of code Unlike regular code, they do not end with a ;
What is a vector? 3
Sequence: Elements in sequence containers are ordered in a strict linear sequence. Individual elements are accessed by their position in this sequence. Dynamic array: Allows direct access to any element in the sequence, even through pointer arithmetics, and provides relatively fast addition/removal of elements at the end of the sequence. Allocator-aware: The container uses an allocator object to dynamically handle its storage needs.
explain std::cout
Std:: reffering to namespace which is collection of methods and objects. Std::cout Want to use cout stream of the std space
fstream
Stream class to both read and write from/to files
ifstream
Stream class to read from files
ofstream
Stream class to write on files
how to make friend function
That is done by including a declaration of this external function within the class, and preceding it with the keyword friend
Function Modifiers: constexpr
The compiler should evaluate the results of calling the function at compile time, making this usable with constexpr constants.
Function Modifiers: inline
The compiler should try to embed the code for the function where it is called from, typically for performance reasons. copy and paste the code every spot that is is called so you have the modularity of the function but have performance of it being in the spot. Use inline for functions that are small and called often.
Function Modifiers: Static
The function is not visible outside of its file / translation unit. Usable and visible inside the library not outside.
difference between procedural and object-oriented programming
The key distinction is that procedural languages organize by procedures with data and functionality separate (though sometimes loosely collected into modules), whereas object-oriented languages organize by classes and objects, with data and functionality effectively bundled together
similarity between procedural and object-oriented programming
There is a very similar control flow between procedure and object-oriented programming. Very similar call-and-return mechanisms, in one case using procedures and in the other using methods on classes and objects.
Problem with operator overloading
There is nothing stopping you, for example, for using operator+ for other things; syntactically, your program would still make sense, but it would be much more difficult to understand from a semantic perspective
performance of virtual
This gives flexibility, but costs in performance
Preproceessor Directives: #define
Used to define constants, replaced during compilation. Can also be used to define macros that are also processed before compilation, such as:#define square(x) (x * x)cout << square(2) << endl;
what does virtual do in virtual void sayHello() {}
Virtual makes it dispatch things not statically but virtually and will choose most appropriate method based on what the type of object that it actually is. Making a lot of methods virtual can slow your code down.
Instead of using std::endl you can use
\n
A friend class definition
a class whose members have access to the private or protected members of another class
Templates
a generic way of writing functions and classes that are capable of operating on more than one data type without having to duplicate the code
Copy constructor definition
a special constructor in C++ that creates an object by initializing it with another, previous initialized object of the same class
A derived class is concrete if and only if
all inherited pure virtual methods are implemented
Explain int *p; p = foo1; cout << foo1[0] << end; cout << *p << endl;
an integer pointer p and now the array can be treated as a pointer here another way of looking at it is foo1 == &(foo1[0]). The two cout print the same thing
Explain int *p; p = &(foo1[2]);
an integer pointer p then have p point to second element.
Limitations of Extraction: The >> operator skips
any leading whitespace characters such as blanks and newlines
Every object in C++ has access to its own address through the use of a pointer
called this
Format of classes in C++
class class_name{ access_specifier_1: // more on this soon member1; access_specifier_2: // more on this soon member2; ... } object_names;
To define a derived class, we use a class derivation list to specify the base class(es); a class derivation list has the form:
class derived‐class: access‐specifier base‐class and if access specified is not used then it is private by default
Abstract classes
classes that have one or more pure virtual methods. classes cannot be instantiated and are used to serve as base classes for other derived classes
constexpr constants
constant expressions evaluated at compile time, allowing them to be placed in read-only memory or to improve performance (new in C++11) ex. constexpr double radius1 = 5.0; (possible to calculate the value at compile time lets say there is function to add 2 numbers, we can calculate that at compile time because it is not like the input numbers we are adding are from user input)
deallocate an array in C++
delete foo;
The direction of the symbols indicates the data's destination: >>
extracts data from an input stream (cin) into a variable
Private and protected members of a class cannot be accessed from outside that class; however, this rule does not apply to
friends
virtual is specified in ___ not in the ___
header file, implementation
When to use virtual
if a method may potentially be overridden
It is also potentially dangerous to use multiple namespaces at a time with using namespace.
if more than one namespace uses the same name, you've got problems. For these reasons, some purists would suggest avoiding this syntax entirely and always explicitly identify scope when required to do so. Preferred to use :: in headerfile then use the namespace in the code.
If the simple implicit copy constructor does not suffice to initialize the object properly on its own, however, you should define one for yourself for example
if your objects contain pointers to other things, you might need to make copies of those other things too, instead of just copying the pointers ...
The C++ Standard Template Library (or STL) provides a collection of general-purpose templated classes and functions that
implement many commonly used algorithms and data structures. The STL is standardized across C++ implementations; for portability and maintainability of code, the STL should be used wherever feasible instead of re-implementing things unnecessarily.
outfile << n << std::flush; Flush causes
input to be forced out quickly. Have print out line and output is buffered and it doesn't appear on the screen and the program crashes in the line after the print statement. This can falsely make you think that your program crashed before the print line but rlly the program crashed after the print line and the output was just buffered.
The direction of the symbols indicates the data's destination: <<
inserts data on to an output stream (cout or cerr)
allocate an array in C++
int size = 5;int *foo;foo = new int[size];
const
is a commitment to not modify something and so the compiler will treat it as a constant and not let us modify it
The only thing that can go on the right of the extraction operator
is a variable, as something is needed to store data extracted from the input stream
Pure virtual methods
methods without an implementation, These are used to force derived classes to implement particular methods
5 steps to building c++ program
multiple source files, C++ compiler (g++), Multiple object files, Linker (Id), executable
const constants
named constant declarations where the programmer commits to not changing a value, and this promise is enforced by the compiler ex. const double pi = 3.14;
Example of a namespace
namespace myNamespace{ int a, b;} or shorthand of using namespace std;
Polymorphism: Notice that the method invoked depends on the type
of the pointer, not what the object actually is. This is typically referred to as static dispatching, as it is determined by the C++ compiler when code is compiled This is the default for efficiency
The fstream library provides the following classes to perform output and input of characters to/from files:3
ofstream, ifstream, fstream
Namespaces: Only one entity can exist with a particular name in a particular scope;
otherwise we have a name conflict or collision
Templates: In a way, the data type becomes a ______ in the definition of the templated function or class
parameter
The this pointer is an implicit
parameter to all member functions, and so inside a member function, the this pointer can be used to refer to the invoking object
#define constants
preprocessor definitions that do a simple replacement during preprocessing and before compiling ex. #define PI 3.14
Class Access Specifiers: private
private members of a class are accessible only from within other members of the same class (this is the default for classes)
Class Access Specifiers: protected
protected members are accessible from other members of the same class and members of their derived classes
Generally, most use cases for inheritance should follow _____ inheritance
public
Defining a member function in a template class
template <class Type> Type calc<Type>::multiply(Type x, Type y) { (The Type calc<Type> is the return type)
Define a template class
template <class Type> class calc {} (You can say <class Type> or <typename Type>)
You can create templates that take more than one type using
template<typename T1, typename T2>
Function Overloading: You cannot overload function declarations that differ only by return type as
the compiler might not be able to determine which version of the function you are attempting to call
If you dont declare a copy constructor
the compiler will typically give you one implicitly that does a simple member-wise copy of the source object You can ask it not to do this, if you don't want it
Static dispatching
the method invoked depends on the type of the pointer, not what the object actually is
Function Overloading: The definition of the function must differ from each other by
the types and/or the number of arguments in the argument list
Static Member Functions
these can be used without having to instantiate objects. As these functions are not attached to particular objects, they do not have a this pointer.
difference between Triangle *tr1 = new Triangle; Triangle tr2;
tr2 is on the stack and tr1 is pointing to something on the heap
A method declared as virtual stays
virtual in all descendent classes. For readability, convention is to continue adding virtual as a reminder, even though it is not strictly necessary.
Example of declaring a pure virtual method
virtual void sayHello() = 0;
Dont need to name parameters
when declaring a function but will name when defined void swap (int *, int *);
Can you make templates of templates?
yes but its bad idea because it can get confusing.
How to make destructor
~Point() { } name of class with tilda