midterm Flashcards

(146 cards)

1
Q

what are records?

A

a struct
- a bundle of information
- several types of data stored together

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

the set values at any given time defines the ______ of a structure

A

state

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

the main point of records/structs is to:

A

treat a number of pieces of data of different types as a unit (that can be passed as a single parameter for example)

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

instance variables are

A

new copies of variables in each specific object that is created

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

ADT’s keep the interface separate from the implementation. The point of this abstraction is to…

A

remove users from the burden of understanding how things are dealt with inside the data structure

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

Example: we have a stack (ADT) implemented in a non-OO language, such as C, using an array.

What are 2 potential issues?

A
  1. Nothing to stop outside code from changing stack internals (no encapsulation)
  2. The code isn’t as generic as it could be (the type of the elements inside the stack has to be defined at compile-time)

What we want from an ADT is independence of interface and implementation

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

_________ are sent to an object (by calling its methods) and then the object responds

A

messages

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

classes define: (2)

A
  • the state information of each object of that class (instance variables – data members)
  • the methods (function members) used by each object of that class

the class itself may have state and behaviours as well (class variables, class methods)

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

Subclasses can ____, _______, ________ any of the methods of its superclass

A

use, modify, replace

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

which keyword is used to define subclasses in Java?

A

extends

eg.
public class Adult extends Person {}

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

A subclass constructor can also explicitly call one of the superclass constructors but it must be declared where?

A

*in Java: as the first statement

Java eg.
public Adult(String name, int age, int s) {
super(name, age);
sin = s;
}

*in C++: declared in initializer
- no “super” keyword

*in JS: before the first use of “this” (usually ends up being the first statement)

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

how can an overridden superclass method be used?

A

Java:
super.func(…)

C++:
SuperClass::method()

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

In some languages a class can have more than one superclass. This is called:

A

multiple inheritance

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

If binding happens during runtime, it’s called ________

A

dynamic

  • unlike static things which occur at compile time
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

T/F:

The class of any object in a variable is fixed at compile time

A

False. OO languages support dynamic class binding

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

Java example:
GraphicalObject go = new Button();

The static type of go is:
The dynamic type is:

A

static type: GraphicalObject
dynamic type: Button

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

To safely cast in Java what keyword should you use

A

instanceof

eg.
if (account1 instanceof SavingsAccount) {
a2 = (SavingsAccount) account1;
}

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

POLYMORPHISM = _____ + _______

A

DYNAMIC CLASS BINDING
+
DYNAMIC METHOD-MESSAGE MAPPING

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

OBJECT-ORIENTED PROGRAMMING = ___ + ____ + ____

A

ENCAPSULATION
+
INHERITANCE
+
POLYMORPHISM

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

If we have dynamic class binding, we also need “Dynamic ____________”

(also known as dynamic dispatch)

A

(Dynamic) Method-Message Mapping

  • Where in the hierarchy do we start when we send a message to an object?
  • must jump to dynamic type and move our way up to find the right method to invoke
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

OOP advantages: (4)

A
  1. Often matches the problem domain nicely
    - mimicry of physical (concrete) OBJECTS
  2. software and code reusability
    - Within a program, inheritance allows common behaviours to be implemented once
    - between programs - A common set of classes for standard tasks can be used by many programs
  3. understandability and maintenance
  4. ease of design
    - eg. subdividing the problem
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

what is shadowing?

A

when you redefine the same instance variables in subclasses

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

with shadowing do you get the version of the static or dynamic type

A

static type.

this is the opposite of what we get when we override methods

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

int x = 1;
int* intPtr = &x ; /* points to _________ */
intPtr = 5; / follow pointer, assign 5 to _________ */

A

the location of x

what it points to (x)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
the arrow operator in C++ ___________ the object you use it on eg. int value = myNode -> data;
dereferences eg. myNode is dereferenced and "data" is retrieved same as: (*myNode).data
26
If we don't properly reclaim memory, it is unusable for the rest of the program’s life. This is called a ____________
memory leak
27
to avoid memory leaks you must remember to free pointer's memory before it...
goes out of scope
28
Inheritance can be considered a _____ relationship
is-a * a BMW is a Car * a SavingsAccount is a BankAccount * a GradStudent is a Student
29
containment can be considered a ______ relationship this is also called __________
has-a composition * a Car has an Engine * an Employee has a Supervisor * a Person has a Spouse (another Person)
30
Classes can be either: * _______ (fully implemented, meant to be instantiated) * ________ (providing elements to be inherited by subclasses, not meant to be instantiated itself)
concrete abstract
31
Abstract classes are defined in java by adding the ________ keyword. How are they defined in c++?
abstract eg. public abstract class ListItem {...} in C++: must have one pure virtual method - virtual void print() = 0;
32
A method can/can't be defined as abstract in a concrete class
can't
33
if Child is a subclass of Parent, then instances of [Parent / Child] can be substituted by instances of [Parent / Child] with no observable effect This is called the Liskov Substitution Principle
parent, child
34
_______________ is what allows the language to look up what the variable really contains at runtime
Dynamic Class Binding
35
in c++ the .h file is the __________ and the .cpp is the ___________ (interface vs implementation)
interface implementation
36
in C++, how does using an initializer in a constructor improve performance? eg. MyNumber::MyNumber() : value(0) {}
normally, when assigning a value to an object variable, a temporary object is created using a null constructor. That temporary object is assigned to the object variable and then destroyed. When using the initializer, this doesn't happen. No call to the null constructor, no temporary object.
37
#include is called a _____________ command
preprocessor
38
what are preprocessor commands?
lines that start with # that are interpreted before compilation begins
39
"using namespace std” is sometimes considered as bad practice, because...
of potential collisions that you could get from using other namespaces at the same time You can do instead: using std::cout; using std::endl; using std::string; for the identifiers you need the most, or just use std::[somethingFromStd] directly in the code.
40
in C++, when one file needs to know about another, we use what to copy in the source from that file?
-#include "file.h"
41
In C++, What do we use to help protect from including something more than once by mistake?
“#pragma once” - replaces guards
42
in C++, always include as much/little as possible
little
43
T/F: “#pragma once” protects against circular includes
false “#pragma once” does NOT protect against circular includes
44
If you include a header file twice and there is executable code in it, you can get two copies of executable code in your compilation, and link editor errors What's a simple solution to avoid this problem?
don't put executable code (inline methods) in header files
45
when to use #include: (4)
1. when extending that class (need to know about members of the superclass) 2. when implementing that class (need to know about own members) 3. when making an instance of another (need to execute the constructor of another class) 4. when invoking any method of another class (need to execute the code of that method)
46
when do we use a forward reference instead of #include?
when you don't need access to the code of a class and just need smth as a parameter type, return type, or instance variable type
47
why should you be careful with arrays in c++
because there is no runtime bounds checking it is easy to get errors similar to those associated with pointers
48
what keyword is used in Java and C++ to self reference? When do you need to do that?
this 1. pass self as argument 2. deal with ambiguity when a local data member shadows the data member of the object - eg: constructor when you do "this->num = num;"
49
the heap is where all _________ memory comes from in any language
dynamic
50
How can memory in the heap be reclaimed in Java and C++
Java: it's garbage collected C++: using "delete"
51
stack-based storage: what you get when variables are declared with...
a specific scope and lifetime according to the variable declaration rules of the language
52
A pointer (object reference in Java) is normally a _____ based variable. The memory it points to is on the _____
stack heap
53
primitive types are ______ based - heap - stack
stack
54
Object references can be _____ -based (declared in methods as local variables), or inside objects (e.g., pointer to another node) but the object themselves are not on the ______ - heap - stack
stack, stack
55
Objects in C++ can be heap-based or stack based. Which way is the following code implemented and how would the other be implemented? //_____-based MyNumber* ptr; ptr = new MyNumber; ptr->print();
heap // stack based MyNumber num; // no () num.print();
56
inheritance how do you define a class as a subclass? In Java and in C++ eg. class Circle is a subclass of class Shape
Java: public class Circle extends Shape {} C++ class Circle : public Shape {}
57
when creating a subclass in C++ you need to include what
the header file of the superclass -#include "superclass.h"
58
how do you "turn on" polymorphism in C++? how is this different from Java
define virtual method in header file in Java, polymorphism is always on
59
When a virtual method is called through a pointer to an object, C++ determines which version of the method to call based on the type of the object actually pointed to at ________ (when?)
runtime this uses dynamic class binding + dynamic method-message mapping
60
In C++, there are two conditions to using polymorphism. What are they?
- must have virtual method in header file to activate polymorphism - must use pointer to call virtual methods. can't be used on stack-based objects
61
In C++, what safety mechanism can you use to ensure you provide a specific implementation of a virtual method?
use override keyword in header file eg. void print() override;
62
What is reverse polymorphism? How is this done in Java and C++?
downcasting (casting down the hierarchy), to access methods specific to the subclass. Should always do safely. Java: instanceof eg. if (pet instanceof Dog) {...} C++: dynamic_cast eg. Animal* aPet; aPet = new Dog; Dog* d = dynamic_cast(aPet); if (d != nullptr) {...}
63
Dynamic Class Binding For a variable, The declared type is the ______ class of that variable. The type assigned to it is the ________ class.
static dynamic eg. Animal* aPet = new Dog;
64
what are the 3 ways a subclass can replace methods from a superclass?
shadow, override, redefine
65
In method shadowing, the signatures are the same in parent and child methods, but...
the method is not virtual (ie. not polymorphic)
66
In _____, shadowing of both methods and data members is possible. How come? (which language)
C++ - polymorphism isn't always on in C++ - done at compile time
67
How do you forbid overriding in Java and C++?
"final" keyword Java: class Parent { public final void method() {....} } C++: void method() final; // forbid overriding method class MyClass final { ... }; // forbid creating subclass
68
If the type signature of a given method name differs from parent to child, then we're doing ___________ (hint: one of the 3 ways a child class can Replace a method)
redefinition
69
When a child's method has an argument that is more specific than the one in its parent's method, we say that it is a __________ argument bonus: whats the opposite? (more general)
covariant opposite: contravariant argument in Animal class: void method(Animal a) in Dog class: void method(Dog d) // Dog is more specific
70
Co/contra-variance is technically ___________ (because it’s a different signature)
redefinition
71
C++ allows some lenience with non-variance – but only in ____________, not __________, and only for ___________ changes words: - arguments / return types - covariant / contravariant
return types, arguments, covariant (Java also allows covariant return types when overriding methods since version 1.5)
72
In general you should always try to follow conventions of __________ even if a language allows otherwise variance / non-variance
non-variance
73
what is refinement?
when a method in a child class has some work handled by the parent class For example: - building a new object of a subclass requires us to do some initialization that the superclass handles - a print method in a subclass requires printing what the superclass was printing + the newly added fields
74
What is the syntax for calling a parent class method in Java and C++?
super.print() // Java ParentClass::print() // C++ - super keyword does not exist in C++
75
Why does the super keyword not exist in C++?
Because C++ allows multiple inheritance. (there's potentially more than one superclass so using super would be ambiguous)
76
Why use refinement
- let's parent classes handle their own data (responsibility) - reduces code duplication
77
what keyword is used to define data members that belong to the class (not instance variables) (keyword is the same for both Java and C++)
static
78
what are the four things every C++ class should have according to OCCF
- a null constructor - a destructor - a copy constructor - an assignment operator
79
why is it important for a destructor to be polymorphic? what could happen if we dont?
Because the pointer to an object could hold an instance of a subclass - we want THAT destructor. otherwise, could have memory leak When a destructor is called using polymorphism the lowest level gets called which automatically calls the parent destructor and so on
80
Which of the following does not involve taking data from another object? Person p = q; Person q("Ryley"); Person r(p);
2nd line: Person q("Ryley"); The other two are calling a copy constructor
81
A copy constructor looks just like a constructor, but it takes a _________ parameter rather than a value parameter
reference
82
a ______ parameter is allocated when the routine is called, and receives a copy of the argument from the call * this is the only way of passing parameters in Java a __________ parameter is a pointer managed internally - it refers/points to the argument from the caller (and thus allows changes to that argument)
value reference
83
In C/C++, things are passed by [reference / value] unless we say otherwise. What operator do we use to say otherwise?
value & operator allows us to pass by reference - supplies the address of the argument instead of a copy of the data
84
why does passing by reference save time?
instead of copying an object (that is potentially large) we pass a pointer instead
85
what keyword can be used to ensure variables aren't changed in a method in C++
const void dostuff(const int& x) {....} // illegal to change x void doStuff() const; // ensures method doesn't change ANY data members of the object belongs to
86
A copy constructor always takes a __________ parameter to the object that must be copied
reference
87
a ______ is a template for the creation of objects
class
88
unlike records/structs, classes support... (3)
1. Encapsulation (restricting access to some fields, information hiding) 2. Variables, behaviours at the class level (class variables, class methods – “static” in Java) 3. Relationships to other classes (hierarchies, inheritance)
89
explain what messages are and what's important about them. how do they relate to methods?
- an important part of OO design - messages are sent to an object by calling its methods and then the object responds - methods define how an object responds to a message - methods send messages to other objects for things that that object is responsible for - sender of the message doesn't need to know or worry about what's done internally - messages can have parameters
90
classes group together...
data and function members (methods)
91
all objects belong to...
some class
92
classes are hierarchal. what is that useful for?
inheritance
93
What is overriding?
When a subclass defines the same method as a parent method (same signature) - superclass version can still be called Java: super.myMethod()
94
class Person {public boolean validate() {}...}; class Student extends Person {public void showGpa() {}...}; class Test { public static void aMethod(Person p) {}... } which are legal? 1. Person p; Student s = new Student(); 2. s.showGpa(); 3. p=s; 4. Test.aMethod(s); 5. p.showGpa(); 6. boolean x = p.validate(); 7. x = s.validate();
All but (5) are legal
95
With polymorphism the method to be invoked by a message is determined at __________
runtime
96
With polymorphism the method that a message maps to depends on the variable's...
the current contents of the variable (dynamic type) the variable's inheritance patterns
97
how is software and code reusability important within programs and between programs?
within programs: - common behaviours only need to be implemented once between programs: - a common set of classes for standardized tasks can be used for many programs
98
what's a common mistake that might happen if you forget that inheritance happens in your hierarchy of classes?
shadowing - you may accidentally redefine instance variables in subclasses
99
because many things must occur at runtime, what type do OO languages use the most
pointers / object references - implicit in Java and JS
100
In Java, most of the operations for pointers are not explicit (3 examples) hint: creation, deletion
* Ask for memory dynamically (using ‘new’) * Don’t explicitly dereference pointers (in C++ we use the arrow) * automatic garbage collection (in C++ we use delete on heap-based objects)
101
the arrow operator in C++ is shorthand for: use example: Object p = new Object; p->doSomething(); //rewrite this line
(*p).doSomething()
102
Why do we typically only use the arrow operator on messages?
because you shouldn’t access fields from other classes (only constants)
103
In C++, to correctly free memory we must...
- use delete - define our own destructor to handle deleting objects within a class
104
T/F A method can be defined as abstract in a concrete class
False we'd have to both leave the method open for subclasses, AND fill it in here, in which case it would appear subclasses could get our filled-in method... it doesn't make any sense
105
If we didn’t have abstract classes is polymorphism still possible?
yes - you would just be able to create an instance of classes that are intended to be abstract - subclasses could omit certain methods that could have been enforced otherwise. (could print an error message in the superclass version...)
106
what is separate compilation?
in C++ we have a .h and .cpp file for each class in which we separate the interface from the implementation
107
T/F C++ allows inline definition of methods
True. but don't do this (defining methods in .h file)
108
the .h file is called the ________ and includes:
Interface * the access modifier sections (public/protected/private) * instance variable declarations * the method headers * guards * includes .h file of any parent class (if applicable) * semicolon after the last }
109
* .cpp file for the implementation includes:
* the full method signatures * the body of the methods * includes (must have .h of this class)
110
Constructors are typically overloaded – (what does that mean)
they have multiple definitions that are disambiguated by different parameters used
111
T/F When using a null constructor in C++, typically we use no brackets
True. but brackets are legal E.g.: MyNumber* mn = new MyNumber;
112
What is the initializer in C++. What is it used for?
initialization of variables done in the header eg. MyNumber::MyNumber() : value(0) {} - calling super constructor - improves performance of creating objects
113
how do we print to console in all three languages? example used in answer: total: 5 (treat 5 as a variable)
Java - System.out.println("total: " + data) C++ - << "total: " << data << endl; - ( must #include iostream) JS - console.log("total: ", this.#data);
114
important libraries to remember for C++?
iostream - printing and strings string - strings eg. #include using namespace std;
115
Unlike Java, in JS it is safe to compare strings using what
the == or != operators
116
what are namespaces in C++? what namespace do we use for iostream and string?
a way to group related code under a named scope to avoid naming conflicts std:: is used for iostream stuff and string. - "using namespace std" allows us to not have to put "std::" in front things it applies to
117
#pragma once means
this file should only be included once
118
when you do a “new” in Java or C++, the object that is allocated is on the _____
heap
119
Activation Records * A pointer (object reference in Java) is normally a ______ based variable (i.e. a normal local variable) * The memory it points to is on the ______
stack heap
120
creating heap-based vs stack-based objects in c++
heap-based - use arrow operator - must explicitly "delete" stack-based - working with objects directly - looks similar to Java - use dot instead of arrow - putting () on null constructor would turn it into a forward reference - no explicit memory disposal needed (destructor gets called when variable goes out of scope)
121
If we can create stack-based objects in c++ why use heap-based at all?
pointers are necessary for the dynamic parts of OO design
122
T/F When a method is pure virtual in a superclass, concrete subclasses can't compile without an implementation of the method
False. It will still compile as long as your code never makes an instance of that subclass
123
T/F You can have an implementation of a pure virtual method in the class that defines it
true. but typically you would not do this
124
(C++) What if the class I want to be abstract has no methods?
You could technically make a dummy method that is pure virtual and does nothing but we generally have at least one method that we make virtual: a destructor
125
what happens if a subclass is passed a message for a method it has no definition for?
it gets passed to the superclass
126
what are class variables? how do you create them
variables that belong to the class as a whole - no separate copies for each instance use static keyword
127
with class members/methods, we can access members/methods through...
the class name or any instance, since these are the same members for all instances
128
Class data members in C++ * they don't exist in any specific instance, so where physically are they placed? * Because there can be confusion having >1 at the global level, C++ forces you to initialize static members where?
- they exist outside all instances when compiled - outside the body of any class you define So in a class, private: static int count = 0; is illegal (declaration ok, but assignment not allowed)
129
How do you initialize a class variable in C++? example: class Counter { private: static int count; public: static void setcount (int); static void showcount(); };
(in .cpp) int Counter::count = 0; the data member is private but looks as if it is being changed outside the definition of the class but it's not – the class Counter::count is saying this code IS part of the definition of class Counter
130
class members in c++ In general, stick to referring to static members using _________ rather than _________
- the class name - an instance makes the fact that it is a static item obvious
131
class members in c++ The declaration of any static data member inside a class does not actually allocate any memory for it. So what must we do? What kind of errors do we get if we don't?
YOU need to ensure that this memory is allocated through an assignment statement outside the class definition we get link editor errors since there is no memory to link to
132
what's the syntax for making a destructor in c++?
~ClassName()
133
what is a reference parameter?
a reference parameter is a pointer managed internally - it refers/points to the argument from the caller (and thus allows changes to that argument) For practical purposes it is just saying “allow the argument to be alterable
134
why use reference parameters? what's the danger in using them?
- saves a great deal of time and space to pass a pointer rather than a copy of a big object danger is that they are changeable, but we can use const to ensure they aren't changed
135
const can be put on a method name to prevent any data members inside from changing. what kind of methods does this always apply to?
getters / accessors eg. int getAge() const; - must have const in .h and .cpp file
136
a copy constructor always takes what as a parameter?
a reference parameter to the object that must be copied eg. Book::Book (const Book& source) { title = source.title; // use dot author = source.author; } - use const cuz we're not modifying the source If Book were organized as a subclass of Item, we would need to call the superclass copy constructor: Book::Book (const Book& s): Item (s) {...}
137
what does the default copy constructor do?
does a recursive copy of fields - every simple field is copied directly (ints, pointers) - every object that isnt a pointer has its copy constructor called
138
why isn't a copy constructor a deep copy by default?
deep copies consume time and memory, so don't do them unless you need to
139
copy constructor will be called whenever we make an object that involves taking data from another object * Person p(q); * Person p = q; But there are also two places where we make a copy of an argument implicitly:
* When passing the object as a value parameter (a value parameter always makes a copy of its data) * When returning an object of this type as a result of a method
140
why is OCCF important?
assignment, null constructor, destructor, and the copy constructor collectively support many higher-level operations. if they don't work the way they are supposed to for your class then many higher level behaviours won't either
141
Assignment in C++ Default behaviour for = on objects (not pointers) is
copy fields recursively (i.e. exactly what the default copy constructor does – i.e. not a deep copy)
142
Assignment is actually a ________ sent to the object on the left/right of the =, with the object on the left/right as an argument
message left, right assignment looks mostly like any other method when we override it: MyObject& MyObject::operator = (MyObject& right) { data = right.getData(); //copy over whatever else we want return (*this); }
143
Assignment in C++ p = q; is a message sent to p asking it to ________
“set itself using q”
144
why does polymorphism rely on the language supporting dynamic class binding and dynamic method-message mapping?
messages will be sent to whatever instance is actually contained in that variable at the time
145
with polymorphism, responsibility is delegated to...
modular subclasses
146
Finish creating class data members // in Counter.h private: // count variable public: // showCount method // in Counter.cpp // code here for count // code here for showCount
// in Counter.h private: static int count; public: static void showcount(); // in Counter.cpp int Counter::count=0; //initialize count! void Counter::showcount() {cout <