CS201 Exam 2 Review

अब Quizwiz के साथ अपने होमवर्क और परीक्षाओं को एस करें!

Inheritance...

The capability of a class to derive properties and characteristics from another class. Is one of the most important features of object-oriented programming. • Inheritance provides a means of specifying general behavior for a set of classes. • It is the process by which a new class(derived class) is created from another class(base class). • The derived class(child) will have. • all the member variables. • all the member functions that the base class(parent) has. • can have additional member functions and member variables. • The child class can have child classes of its own.

Linked Lists...

Pointer to header Add a value to end Add a value to middle Add a value to beginning Remove a value from end Remove a value from middle Remove a value from beginning Delete List

Pass by Value Pointers in Functions...

Pointers can be used as function parameters void function(int a, int *p); p can be pointing to a variable (int, double, object, array, vector) p is passed by value, so the function gets a copy of contents of p (the address of the variable). If you call delete pin the function, it deletes the data, and the caller doesn't know it's gone.

Abstract Data Type...

Represent the needed information in program without presenting the details. So, it depends on the separation of interface and implementation.

Constructor Initializer List...

So instead of: Student::Student() { name = ""; ID = 0; GPA = 0.0 } Use this: Student::Student():name('');ID(0);GPA(0.0){}

Classes in main: //define objects of type student...

Student record1; Student record2("Albert Einstein", 4.0, 0001); cout << record2.getName() << endl;

Dangling Pointer...

after you apply delete to a pointer variable, the dynamic variable to which it is pointing is destroyed. So the value of the pointer variable is undefined, which means you don't know where it is pointing. So if you tried to apply the dereference operator * to pointer (*p) the result will be unpredictable. So the value NULL (or nullptr on newer compilers) should be assigned to a pointer once when it's declared, and also after deleting a pointer. int *p1 = nullptr; p1 = new int; // do your program delete p1; p1 = nullptr;

Array variables...

are actually pointer variables that point to the first indexed variable of the array. int m[5]; int &p; Both m and p are pointer variables. M is a pointer that points to a variagble of type int, the value of a can be assigned to the pointer p p = m; // p points to the same memory lcoation // that m points to

Which constructor will be called by the statementHouse myHouse(12); for the given code? class House { House(); //Constructor A House(int num, string str); //Constructor B House(int num1, int num 2); //Constructor C House(int num); //Constructor D }; a. Constructor A b. Constructor B c. Constructor C d. Constructor D

d. Constructor D

Which XXX would make the class People an abstract class? class People { protected: string name; int age; public: XXX }; class Teacher : public People { private: int experience; public: void PrintInfo(); }; class Student : public People { private: int grade; public: void PrintInfo(); }; a. void abstract People() = 0; b. virtual void PrintInfo() const; c. void abstract People() const; d. virtual void PrintInfo() = 0;

d. virtual void PrintInfo() = 0;

Which of the following is the proper LinkedList class destructor? a. void ~LinkedList(delete); b. ~LinkedList(int); c. void ~LinkedList(); d. ~LinkedList();

d. ~LinkedList();

Delete...

eliminates a dynamic variable and return the memory that the dynamic variable occupied, so that the memory can be reused. delete p; //this will destroy the dynamic variable pointed to by p int *p3; p3 = new int(30); cout << "*p3 = " << *p3 << endl; delete p3;

Destructors...

used to deallocate space for an object care for sub-objects that allocate additional memory -both object & the sub-object must be explicitly deleted

Pointers Passed as Reference Sample...

void output_result(int* &value) { value = new int(*value + 1); cout << "&value: " << &value << "\t value: " << value << "\t*value: " << *value << endl; } void main() { int* x = nullptr; x = new int(80); cout << "&x: " << &x << "\t x: " << x << "\t *x: " << *x << endl; output_result(x); cout << "&x: " << &x << "\t x: " << x << "\t *x: " << *x << endl; }

Pointers Passed as Value Sample...

void output_result(int* v) { *v output_result(int* v) { *v = *v + 1; cout << "&v: " << &v << "\t v: " << v << "\t *v:" << *v << endl; } void main() { int* x = nullptr; x = new int(80); cout << "&x: " << &x << "\t x: " << x << "\t *x: " << *x << endl; output_result(x); cout << "&x: " << &x << "\t x: " << x << "\t *x: " << *x << endl; }

Private/Protected...

• A member variable that is private in a base class is not accessible by name in any other class, not even in the member function definition of a derived class. • ex: name in HourlyEmployee is a private member variable in Employee class. • So, name can only be accessed within the definition of member function of class Employee. • To use the name in the HourlyEmployeederived class, you need to use the public member function to access the member variable (getter).

Nondefault Constructor...

• For non-default constructors of a derived class(HourlyEmployee), there is a special syntax for invoking the base class constructor(Employee).

Redefining Versus Overloading...

• In redefining a function definition, the new function in the derived class has the same number and type of parameters. • In overloading a function, the function in the derived class will have a different number of parameters or a different parameter type from the function in the base class. • And the derived class will have both functions.

Static Members...

• Not associated with an object, but with the class. • An object does NOT need to be created for this member to exist or be utilized. • Memory allocated 1 time during program execution. • Global scope.

Operator Overloading...

• Redefining what '+' or '==' mean for a class? • Hours & Minutes • 4 hours and 20 minutes + 50 minutes = 4 hours and 70 minutes?? or 5 hours and 10 minutes • 5 hours and 37 minutes + 2 hours and 40 minutes = 7 hours and 77 minutes?? THM THM::operator+(THM t2); main() { THM time1(5, 37); THM time2(2,40); THM total; total = time1+time2 }

Polymorphism...

"Having many forms". The ability of a message to be displayed in more than one form. EX: a person at the same time can have different characteristics.

Sample of Derived Class...

#include "employee.h" class HourlyEmployee :public Employee { public: HourlyEmployee(); HourlyEmployee(const string& theName, const string& the Ssn, double wage, double h); void setWage(double newwage); double getRate() const; void setHour(double hoursW); double getHour() const; void print; private: double wageRate; double hours; }; 1. HourlyEmployeereceives all the member variables and member functions of Employee class. 2. The definition of HourlyEmployee doesn't mention the member variables but every object of the class has member variables named name, ssn, and payrate.

Uses attributes and methods...

(*var).attribute or var -> attribute

Accessor Functions (Getters) are...

...able to return object values. string getName() { return name; } int getID() { return ID; } double getGPA() { return GPA; }

Mutator Functions (Setters) are...

...able to update object values. void setName(string n) {name = n; } void setID(int id) {ID = i; } void setGPA(double g) {GPA = g; }

Private Members...

...are all the items that follow the word private can't be referenced by name anyplace except within the definition of the member functions of the class. class Student { public: void setName(string n); string getName(); void setGPA(double grade); private: string name; int ID; double GPA; };

Public Members...

...are all the items that follow the word public can be used anywhere in the programs utilizing the class. class Student { public: void setName(string n); string getName(); void setGPA(double grade); };

Inline member functions...

...are short functions that is a part of the class header .h file.

Freestore (Heap)...

...is a special area of memory that is reserved for the dynamic variables. Any new dynamic variable created consumes some of the heap. If you create too many dynamic variables, then it will consume all the memory in the heap. Any additional call for the new operator will fail. And an exception is thrown.

Computer memory is...

...is divided into numbered memory locations.

By using call by reference arguments...

...it passes the address not the identifier name of the variable.

Variables are...

...the names given to memory location (holding a value). int v = 15 int *p1; p1 = &v; //sets the value of p1 so p1 points to the var. v *p1=50;

If we have a collection of variables...

...we can refer to the item at a particular address.

Code...

...where program instructions are stored.

Derived Class...

1. HourlyEmployeeadded: a) two more member variables, so every object of the class has five member variables. b) four member functions. 2. NOTE: HourlyEmployeedeclared the print() function which means that you will need to change the function definition. 3. So, you don't give a declaration for the inherited member functions unless the definition of the member function is changed in the derived class (HourlyEmployee).

Multidimensional Dynamic Array...

An arrays of arrays (2D dynamic array) To create 2D dynamic array of integers: First create one dimensional dynamic array of pointers of type int*. Second, create a dynamic array of ints for each element of the array.We can create such an array dynamically by using a pointer to a pointer.

Creates a new instance...

Class *var = new Class;

Classes in Student.cpp: definition...

Default Constructor -> Student::Student() { Overloaded Constructor -> Student::Student(string n, double g, int i) { #include <string> #include "Student.h" using namespace std; Student::Student() { name = ""; GPA = 0.0; ID = 0; } Student::Student(string n, double g, int i) { name = n; GPA = g; ID = i; } string Student::getName() { return name; }

Information Hiding...

Information that is not needed by the rest of the program can be kept private.

Encapsulation...

It combines the data and functions inside a class. hides the data from being accessed from outside a class data can only be accessed through the functions inside the class.

Dynamic Arrays...

When using arrays you need to specify the size of the array. But sometimes you don't know the size of the array until the program runs. So you can use dynamic arrays, where the size can be entered as input to the program. Dynamic arrays are created using the new operator. int *p;p = new int[10]; If you omit the brackets and 10 then the computer will allocate enough storage for one variable of type int. int *p; p = new int[10]; for (int i = 0; i < 10; i++) { p[i] = i * 2; court << p[i] << " "; } delete[]p; p = nullptr;

Virtual Function...

a member function that may be redefined in the derived class or overridden in the base class. ex: virtual void print() const; At runtime, when a virtual function is called using a pointer, the correct function is determined depending on the object type to which the pointer refers the virtual function in the base class is implemented (defined) and then in the derived class, you have the same virtual function but implemented(overridden) in a different way. For any object of the derived class, that object will always use the definition of the virtual function that was given in the derived class. Even if the virtual function is used in another inherited function. Polymorphism -> Compile Time & Run Time Compile Time -> Function Overloading & Operator Overloading Run Time -> Virtual Functions

What is the return type for constructors? a. None b. char c. void d. int

a. None

The __________ construct defines a new type to group data and functions to form an object. a. class b. struct c. array d. library

a. class

Which statement is true about inheritance? a. A derived class cannot serve as a base class for another class. b. A class can serve as a base class for multiple derived classes. c. A class can be derived from only one class. d. A class can serve as a base class for only one class.

b. A class can serve as a base class for multiple derived classes.

Which of the following is true if a programmer has to create a class Clinic with the following data members and functions? class Clinic { int patientRecNum; string patientName; void Set Details(int num, string name); Clinic GetDetails(); }; a. Data members should be public items and function declarations should be private items. b. Data members should be private items and function declarations should be public items. c. The data member patientName should be a private item and all other members should be public items. d. The function SetDetails should be a public item and all other members should be private items.

b. Data members should be private items and function declarations should be public items.

The codes for class Hotel has been defined in two separate files Hotel.h, and Hotel.cpp. Which of the following statements is true? a. Hotel.cpp contains the class definition with data members and function declarations. b. Hotel.cpp contains member function definitions and includes Hotel.h. c. Hotel.h contains the class and member function definitions. d. Hotel.h contains the class definition with only data members.

b. Hotel.cpp contains member function definitions and includes Hotel.h.

Consider a classStudent. The following code is used to create objects and access its member functions. Which statement is true about the code? int main () { Student new Stud; Student stud; Student old Stud; stud.GetDetails(); return 0; } a. There are three objects created of Student class and they each have their own memory allocations. The GetDetails() function is invoked for all objects of the class Student. b. There are three objects created of Student class and they each have their own memory locations. The GetDetails() function is invoked for only the stud object of the class Student. c. There are three objects created of Student class and the compiler allocates only one memory location. The GetDetails() function is invoked for only the stud object of the class Student. d. There are three objects created of Student class and the compiler allocates only one memory location. The GetDetails() function is invoked for all objects of the class Student.

b. There are three objects created of Student class and they each have their own memory locations. The GetDetails() function is invoked for only the stud object of the class Student.

What is output? #include <iostream> using namespace std; class Players { public: string name; void callPlayer(Players* ptr) { cout << "This player is called at runtime - " << ptr->name << endl; } void callPlayer(string playerName) { cout << "Calling player " << playerName << endl; } void callPlayer() { cout << "No player to call!" << endl;} }; int main() { Players* playerPtr = new Players(); Players newPlayer;playerPtr->name = "Tim";newPlayer.callPlayer(playerPtr); return 0; } a. Calling player Tim b. This player is called at runtime - Tim c. No player to call! d. Error: runtime error

b. This player is called at runtime - Tim

Which statement properly frees the dynamically allocated array below? Musketeer* musketeers = new Musketeer[8]; a. delete musketeers; b. delete [] musketeers; c. musketeers->delete; d. musketeers* musketeers = delete musketeers;

b. delete [] musketeers;

hen a class derives the properties of the base class, the concept is called _____. a. branching b. inheritance c. overlapping d. streaming

b. inheritance

Declaring a member as ____ in the base class provides access to that member in the derived classes but not to anyone else. a. public b. protected c. private d. constant

b. protected

In the following code, what is the correct return statement for an overloaded + operator? Game Game::operator+(Game newGame) { Game myGame; myGame.score = score + newGame.score; } a. return Game; b. return myGame; c. return newGame; d. return score;

b. return myGame;

Assuming a class Student has been defined, which of the following statements is correct for declaring a vector? a. vector[Student] studList; b. vector<Student> studList; c. vector Student studList; d. vector (Student) studList;

b. vector<Student> studList;

The copy constructor makes a new copy of all data members (including pointers), known as a _____. a. neat copy b. shallow copy c. deep copy d. reference copy

c. deep copy

Which of these will properly overload the assignment operator? class BookLog { public: BookLog(); BookLog& operator=(const BookLog& objToCopy); void SetBookCount(const int setVal) { bookCount = bookCount + setVal; } int GetBookCount() const { return bookCount; } private: int bookCount; }; BookLog& BookLog::operator=(const BookLog& objToCopy) { XXXreturn *this; } a. if (this = &objToCopy) {bookCount = objToCopy.bookCount;} b. if (this != objToCopy) {bookCount = objToCopy.bookCount;} c. if (this != &objToCopy) {bookCount = objToCopy.bookCount;} d. if (this = objToCopy) {bookCount = objToCopy.bookCount;}

c. if (this != &objToCopy) {bookCount = objToCopy.bookCount;}

Consider a class Student with public member functions and private data members. Which of the code choices below should be used to replace XXX? class Student { private: string name; int grade; public: void SetName(string studentName); void SetGrade(int studentGrade); void Display(); }; int main() { Student stu1; XXX } a. stu1.name = "Harry"; b. myString = stu1.name; c. stu1.Display(); d. stu1.SetName("Harry");

c. stu1.Display(); d. stu1.SetName("Harry");

Heap is a region in program memory where _____. a. the program instructions are stored b. global and static local variables are allocated c. the "new" operator allocates memory d. a function's local variables are allocated

c. the "new" operator allocates memory

Sample of Base Class...

class Employee { public: Employee(); Employee(const string& theName, const string& theSsn); string getName() const; string getSsn() const; double getPayRate() const; void setName(const string& newName); void setSsn(const string& newSsn); void setPayRate(double newRate); void print(); private: string name; string ssn; double payRate; }; So a derived class of Employee will automatically have all the member functions of the class Employee and the member variables (inherits)

Protected/Private/Public Inhertiance...

class Employee { public: int A; private: int B; protected: int C; }; class HourlyEmployee:public Employee { class HourlyEmployee:protected Employee { class HourlyEmployee:private Employee {

Access to Redefined Base Function...

• Say we redefined a function definition in the derived class. • This doesn't mean that the definition of the function in the base class is lost. • We can still invoke the version of the function in the base class with an object in the derived class. • You need to add the scope resolution with the name of the base class when you need to use the function in the base class. Employee Emp1; Emp1.print(); HourlyEmployee Emp2; Emp2.print(); • So now I need to use the object(Emp2) in the derived class to invoke the print() function in the base class(Employee) Emp2.Employee::print();

Default Constructor...

• The constructor for HourlyEmployee() automatically calls the parent's default constructor(Employee) • classes derived from HourlyEmployee() will call its default constructor.

Redefining a Method...

• The definition of an inherited member function can be changed in the definition of a derived class so that it has a meaning that differ from the base class. void Employee::print() { cout << "This function is used to test redefining a function\n"; //base class } void HourlyEmployee::print() { setPayRate(hours*wageRate); cout << "The Employee name is " << getName() << endl; cout << "The Employee SSN is " << getSsn() << endl; //derived class cout << "The Employee payment is " << getPayRate() << endl; }

Protected Qualifier...

• There is another way where member variables and functions are allowed to be accessed by name in the derived class but not accessed anyplace else. • You can use the qualifier protected instead of private or public before member variables and functions. • So, for any class or function other than the derived function, these member's variables and functions will be labeled private. • Now derived classes can access those members by name.• Also, if you have a child class from the derived class, then they all can access the member variables and functions by name.

Constructors...

• These are member functions that allow you to initialize the attribute values in the new object. • They have the same name as the class. Student(); Student (string, double, int)

Constructors in Derived Class...

• We can put the call to the parent's constructor(Employee) right after the child's constructor header(HourlyEmployee): HourlyEmployee::HourlyEmployee(const string& theName, const string& theSsn, double wage, double h):Employee(theName, theSsn) { wageRate = wage; hours = h; }

Pointer...

• a data type that points to the address of a value stored in memory. • can be stored in a variable • A variable to hold a pointer must be declared to have a pointer type. void main() { int *p, v; v = 15; p = &v; *p = 50; cout << "v = " << v << " and *p = " << *p << endl; } type *variableName;

A class...

• combines a blueprint of data (data members/arguments) & functions (methods) that are related. • an object is an instantiated class (when value(s) are assigned to a class type). • classes have public/private access (public access is outside the class). • generally -data members are private and function members are public• the default is private. • similar to a structure type. • structure members by default are set to public.

Static Memory...

• global variables • static local variables • allocated 1 time & stay in the same location during program execution

Stack...

• local function variables • deallocated at the end of the function • aka automatic memory

Copy Assignment Operator...

• overload the = if not defined, the compiler defines one that will do a member-wise copy (shallow copy)

Garbage Collection...

• some languages (java) include behavior that finds unreachable memory and frees the memory as needed • some non-standard C++ implementations will utilize this

Classes in Student.h: declaration...

• the member functions are listed in the class declaration and are generally public. • Member functions can access the class attributes marked private. class Student { public: void setName(string n); string getName(); void setGPA(double grade); private: string name; int ID; double GPA; };

Copy Constructor...

• used when objects are passed by value to a function • ensures the object is properly setup if not defined, the compiler defines one that will do a member-wise copy (shallow copy)

Memory Leak...

• when a program allocates memory & loses the ability to access it • usually happens when you improperly destroy a pointer without destroying the memory it points to • can cause the program to fail if there is no space for additional memory needed


संबंधित स्टडी सेट्स

Unit 2: Structures and Functions of Government Vocabulary

View Set

AP Psych Mini Quiz Questions (All Units)

View Set

(Más Vocabulario) Hola, ¿qué tal?

View Set

Corporate Communication Chapter 1

View Set