Soft eng Flashcards

1
Q

What is binding? What is early vs late binding?

A

Binding: process of matching function calls to their definitions, performed by compiler and linker.

Early binding: Also known as static binding, is the default in C++. Early binding is when the process of binding occurs at compile time.

Late binding: When binding occurs at runtime, during execution of the program.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What is polymorphism? How does binding relate to polymorphism? Illustrate with an example.

A

Polymorphism is the principle of providing a single interface to multiple subtypes via a base class.

Late binding is needed with polymorphism as function calls need to be bound to their matching definitions according to the subtype, not the base class. Late binding is achieved using the word “virtual”.

Example: 
class Base, contains a function disp() which prints "base".
class Derived, inherits from base, contains function disp() which prints "derived".
main function creates a derived object using Baste * ptr = new Derived. 
ptr->disp() prints base. 
If the Base class disp() has the word "virtual" in front of it, ptr->disp() now prints derived.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What are include guards?

A

Include guards are constructs added to header files to prevent multiple inclusion of any identifiers in the header when they get included via an #include directive.

The #ifndef directive tells the compiler to skip over a file if it has been previously included, thereby solving the problem of multiple inclusion.

guards are: #ifndef \_\_\_
#define \_\_\_
...
#endif

Draw dependency tree:
main -> triangle -> point
main -> square -> point

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

If i have an iterator it used on a vector v, how do i find:

Address of iterator?
Element being pointed to?
Address of element being pointed to?
Index in v currently being pointed to?

A

Address of iterator: &it
Element being pointed to: it
Address of element being pointed to: &(
it)
Index in v currently being pointed to: it - v.begin()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Difference between using iterators on a vector of ints vs a vector of templates

A

ints:
std::vector::iterator it = vec.begin();

templates:
typename std::vector::iterator it = vec.begin();

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Explain why the separation of function definitions from their declarations is not possible with template functions

A

A template function is a template for the compiler to use when it encounters a function call with actual parameter types. When compiler instantiates the actual function, it needs the full function definition to perform syntactic checks. This instantiation is performed at compile time, before linking, hence the template function’s definition cannot be seperate to its declaration.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Do you put semicolons after an initialization list in the constructor?

A

No semicolon, only open and closed curly braces.

A(x_in): x(x_in) {}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

friend functions are declared in the class with the friend keyword in front. They are defined outside the class without the friend keyword.

Friend keyword = this function can access my private member data

A

.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

If a function/operator takes a template class as input, what does the defintion look like?

A

Put a template before it, and in the declaration have a after the class name

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What is exception safe code?

A

Exception safe code keeps state consistent and handles resources appropriately even if an exception is thrown.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Exceptions vs exit instruction

A

The exit instruction terminates the whole program and the only information as to the source of the error is the exit code, which is not very informative for the programmer.

Exceptions don’t terminate the entire program - only the current function being executed, and they pass control to the caller for exception handling.

Different types of exceptions, describing different errors and prescribing different handling mechanisms, can also be thrown.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

If an exception is thrown, control goes to the caller and keeps going up until a try block is encountered. In that case no other instructions within the try block are executed and control passes to the catch block.

Destructors of all objects created within scope of try block are called when exiting try block.

A

.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

virtual vs virtual = 0

A

virtual –> base class has an implementation for it. Subclasses, if they override it, will have their own implementation. Function calls will be resolved at run time to the implementation of the object on which they are called.

virtual = 0 –> PURE VIRTUAL, the base class is an abstract class. Every subclass must override this function and say so (using keyword override before {}).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Filled diamond vs empty diamond vs arrow in UML diagram

A

Filled diamond: Composition. When member variables of a class are objects of another class.

Empty diamond: Aggregation. the other class can be useful without the class that is composed of it…?

Arrow: Inheritence. Subset.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Order of catch blocks

A

Most specific to most general, because a specific exception inherits from general exceptions so it will get caught in the first general catch block it encounters.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Access modifiers and differences between them

A
Public: fields are accessible from within and outside the class
Private: fields are accessible only from within the class and by friend functions, not even by subclasses
Protected: fields are accessible within the class and by subclasses
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

Member data represents the state of the object and we only want it to be accessible from within the object and from the outside via abstractions provided by the class –> hence member data is private

A

.

18
Q

Insertion of &laquo_space;operator - is it a member function or global function and why?

A

It is a member function for the ostream class which deals with basic types such as int, float, etc. For all other types and classes (such as strings/user defined types) it is a global function (and possibly friend function).

This is because for a binary operator to be a member function of a class, it has to be a member function of the object on the left hand side of the operator. However with the insertion operator the left hand side is almost always a stream and we would like to override it for the operand on the right hand side. To make the insertion operator a member function of other classes would mean having to re-write it for the standard library which implements ostream, which does not make sense. Hence it is implemented as a global function.

19
Q

Syntax for writing object oriented code

A

When expressing inheritence in code, write

class A {};
class B: public A {};

Within the class put semicolon after any function declarations but not definitions. (as you would outside a class). Semicolons after all variable declarations and definitions.

20
Q

Explain the concept of a type in OOP and how it relates to inheritence.

A

The type of an object is related what operations it can perform/can be performed on it and this is determined by the class it is an instance of.

Since subclasses inherit all the operations of the base class, they are of the same type as the base class.

21
Q

What is an abstract class and what is its role in software engineering

A

An abstract class is one that cannot be instantiated as it contains at least one pure virtual function - a member function which is declared but not defined.

All subclasses to implement their own meaningful versions of the virtual function and the abstract class provides a convenient interface from which to call these functions regardless of the actual object to which they belond (polymorphism).

eg: class Shape{
virtual int calculateArea() = 0;
};
class Square{
virtual int calculateArea(...) {...} };
22
Q

What is the initialization list

A

Initialisation list is a way to initialise member data from the constructor of a class, often using copy constructors of other classes in the process.

eg: class Triangle which contains 3 instances of class Point:
class Triangle{
Triangle(const point& p1_in, const point& p2_in, const point& p3_in): p1(p1_in), p2(p2_in), p3(p3_in) {}
23
Q

Why is an initialization list important

A
  1. Initialising using the copy constructor is more efficient than using a default constructor then overriding using assignment operator
  2. Assignment operator is not available for some types
  3. const member data has to be initialised with initialisation list
24
Q

What are friend functions

A

Friend functions are global functions that are given access to private member data of a class. eg:

class A{
public:
    friend void func(A& a);
private:
    int data;
};
void func(A& a){
a.data = 10;
...
}
int main(){
A object1;
func(object1);
return 0;
}
25
Q

What is operator overloading

A

C++ defines some operators (e.g +, -, <

26
Q

Vectors: difference between v[x] and v.at(x)

A

.at checks if x is out of bounds and throws an exception if so, wheras [] just tries to access the x-1th element.

27
Q

int a = v[5] (v is vector) is same as what using iterators?

A
  1. std::vector::iterator it = v.begin();
    int a = *(it + 5);

or

int a = *(v.begin() + 5);

28
Q

Where is std::list more efficient than std::vector?

A

Inserting an element to the beginning of a list is faster.
insertion and deletion of an element in the middle of a list, using iterators, is O(1), for vector is O(n).
(list implements doubly linked list, non contiguous in memory)

29
Q

Use iterators to go through a template vector

A

Template
void go_thru_vec(const std::vector &vec){
typedef std::vector::iterator it;
for(it = vec.begin(); it!=vec.end; ++it){
std::cout &laquo_space;*it &laquo_space;\t;
}
}

30
Q

Write code that throws and catches exception

A
try{
...
f();
...
}
catch(const string&amp; msg){
std::cout<> n;
if(n<0){
throw string("input value cannot be less than 0");
}
}
31
Q

What is RAII?

A

Resource acquisition is initialisation.
A resource is acquired by the constructor of an associated object and released by its destructor. Works well with exceptions because destructors are called even when exceptions are thrown (because program exits the try block scope).

32
Q

Provide code of a class that obeys RAII

A

The following class contains a constructor, a destructor and a getter function. Status boolean is set to true when the object can update the database (ie the resource has been acquired).

The constructor first checks if the file “.lockdb” exists. If it does, then the object cannot perform updates to the database. If it doesn’t, it creates the file and sets status to true.

The destructor deletes the “.lockdb” file, thereby freeing up the resource.

get_status is useful for other objects to check the status of a particular object.

class Lockdb{
public:
    Lockdb();
    ~Lockdb();
    bool get_status();
private:
    status;
};
Lockdb::Lockdb(){
    ifstream infile(".lockdb");
    if(ifstream_is_open())
        status = false;
        //resource is busy
    else{
        ofstream ofile(".lockdb");
        status = true;
        //locked resource
}
Lockdb::~Lockdb(){
    if(status)
         remove(".lockdb");
//resource freed
}
bool get_status(){
    return status;
}
33
Q

What is the state of an object?

A

Objects contain certain member variables. The state of the object is the combination of values of the member variables. This combination uniquely defines an object. as the values change with time, so does the state of the object.

34
Q

What is inconsistent state and how do encapsulation and abstraction help avoid it?

A

Inconsistent state is when the values of member variables do not agree with each other. For example, if the class contains two public member variables - an x coordinate, y coordinate and a distance to origin. Since these are public, they can be accessed from outside the function. X and Y could be set to 0 but distance set to 1 - inconsistent state.

Encapsulation (using the access modifier private) ensures that x, y and distance are only mutable from within the object itself. Abstraction, using setters and getters, can be used to keep state consistent by updating all member data whenever one member variable is changed.

For example,

set_x(int x_in){
x = x_in;
distance = sqrt(xx + yy);
}

35
Q

UML diagrams: pubic vs private vs protected

Function names, arguments and return types

A

public: +
private: -
protected: #

foo(a: int): void

ALWAYS (+/-/#) name: type

36
Q

Templates: whenevr you call the constructor of a template class, put types in <>.

A
template
class m_pair{
    public:
        m_pair(const T1&amp; f, const T2&amp; s) : first(f), second(s) {
        T1 first;
        T2 second;
};

m_pair mp(3, true);

37
Q

What are memory leaks?

A

Memory leaks occur when dynamically allocated memory becomes unreachable as it has not been deallocated. Repeated occurrences depletes available memory.

38
Q

When and why are function parameters declared const

A

Passing argument by reference saves time over passing by value as we do not need to copy the whole object. However, passing by reference means that the object can be changed by the function. To avoid that risk, we pass by const reference, which prevents the function from altering the object and does not need to copy the object into the function, thereby also making it fast.

39
Q

Why are member functions declared as const

A

Member functions are declared const to indicate that they do not alter the state of the object.

Then, when the object is passed by const reference to a global function, the const member function can be used within the global function because “const” guarantees that the state of the object will be preserved.

40
Q

Stack vs heap

A

Stack: static memory allocation, heap: dynamic memory allocation

41
Q

pointer to const vs const pointer

A

int * const ptr –> const pointer to an int.
the int can be changed but the pointer cannot.
ptr++ //not allowed
*ptr = 5 //allowed

int const * ptr –> pointer to const int
the int cannot be changed but the pointer can
ptr++ //allowed
*ptr = 5 //not allowed

READ RIGHT TO LEFT:
int * const ptr –> ptr is a const pointer to int
int const * ptr –> ptr is a pointer to const int