CSCI 221 Exam 1 conccepts

Ace your homework & exams now with Quizwiz!

Objects as array elements

-Like array of other user-defined data types, an array of type class can also be created. -The array of type class contains the objects of the class as its individual elements. -Thus, an array of a class type is also known as an array of objects. -An array of objects is declared in the same way as an array of any built-in data type. class_name array_name [size] ; #include <iostream> class MyClass { int x; public: void setX(int i) { x = i; } int getX() { return x; } }; void main() { MyClass obs[4]; int i; for(i=0; i < 4; i++) obs[i].setX(i); for(i=0; i < 4; i++) cout << "obs[" << i << "].getX(): " << obs[i].getX() << "\n"; getch(); }

Constructor of a class (Default constructor, overloaded constructors)

A constructor without any arguments or with default value for every argument, is said to be default constructor. In C++, We can have more than one constructor in a class with same name, as long as each has a different list of arguments. This concept is known as Constructor Overloading and is quite similar to function overloading. Overloaded constructors essentially have the same name (name of the class) and different number of arguments. A constructor is called depending upon the number and type of arguments passed. While creating the object, arguments must be passed to let compiler know, which constructor needs to be called.

Friend functions

A friend function of a class is defined outside that class' scope but it has the right to access all private and protected members of the class. Even though the prototypes for friend functions appear in the class definition, friends are not member functions. A friend can be a function, function template, or member function, or a class or class template, in which case the entire class and all of its members are friends. To declare a function as a friend of a class, precede the function prototype in the class definition with keyword friend as follows − class Box { double width; public: double length; friend void printWidth( Box box ); void setWidth( double wid ); }; To declare all member functions of class ClassTwo as friends of class ClassOne, place a following declaration in the definition of class ClassOne − friend class ClassTwo;

Other member functions of a class

A member function of a class is a function that has its definition or its prototype within the class definition like any other variable. It operates on any object of the class of which it is a member, and has access to all the members of a class for that object. Member functions can be defined within the class definition or separately using scope resolution operator, : −. Defining a member function within the class definition declares the function inline, even if you do not use the inline specifier If you like, you can define the same function outside the class using the scope resolution operator (::)

Concept of ADT

Abstract Data type (ADT) is a type (or class) for objects whose behaviour is defined by a set of value and a set of operations. The definition of ADT only mentions what operations are to be performed but not how these operations will be implemented. It does not specify how data will be organized in memory and what algorithms will be used for implementing the operations. It is called "abstract" because it gives an implementation-independent view. The process of providing only the essentials and hiding the details is known as abstraction. The user of data type does not need to know how that data type is implemented, for example, we have been using Primitive values like int, float, char data types only with the knowledge that these data type can operate and be performed on without any idea of how they are implemented. So a user only needs to know what a data type can do, but not how it will be implemented. Think of ADT as a black box which hides the inner structure and design of the data type. Now we'll define three ADTs namely List ADT, Stack ADT, Queue ADT. 1. List ADT The data is generally stored in key sequence in a list which has a head structure consisting of count, pointers and address of compare function needed to compare the data in the list. A list contains elements of the same type arranged in sequential order and following operations can be performed on the list. get() - Return an element from the list at any given position. insert() - Insert an element at any position of the list. remove() - Remove the first occurrence of any element from a non-empty list. removeAt() - Remove the element at a specified location from a non-empty list. replace() - Replace an element at any position by another element. size() - Return the number of elements in the list. isEmpty() - Return true if the list is empty, otherwise return false. isFull() - Return true if the list is full, otherwise return false. 2.Stack ADT In Stack ADT Implementation instead of data being stored in each node, the pointer to data is stored. The program allocates memory for the data and address is passed to the stack ADT. The head node and the data nodes are encapsulated in the ADT. The calling function can only see the pointer to the stack. The stack head structure also contains a pointer to top and count of number of entries currently in stack. A Stack contains elements of the same type arranged in sequential order. All operations take place at a single end that is top of the stack and following operations can be performed: push() - Insert an element at one end of the stack called top. pop() - Remove and return the element at the top of the stack, if it is not empty. peek() - Return the element at the top of the stack without removing it, if the stack is not empty. size() - Return the number of elements in the stack. isEmpty() - Return true if the stack is empty, otherwise return false. isFull() - Return true if the stack is full, otherwise return false. 3. Queue ADT The queue abstract data type (ADT) follows the basic design of the stack abstract data type. Each node contains a void pointer to the data and the link pointer to the next element in the queue. The program's responsibility is to allocate memory for storing the data.

address-of operator (&)

An address-of operator is a mechanism within C++ that returns the memory address of a variable. These addresses returned by the address-of operator are known as pointers, because they "point" to the variable in memory. The address-of operator is a unary operator represented by an ampersand (&).

Array as class members

C-style arrays are pretty primitive, and they don't come with boundary checking. In some ways, they are unsafe, especially in novice hands If an array is used as member data of a class, the member functions can add in error-checking and boundary protection.This is a good technique for creating safer array types -- user defined classes that store large amounts of data Here is the start of such a class, which stores an array of floating point numbersThis class stores a list of up to 10 values of type doubleNote that the array is allocated to size 10, but the list can have up to 10 items in it -- the "list" is not always "full"!This is managed with a tracking variable -- current. This is a member data variable that keeps track of how many elements are in the "list".Note that the "list" and the "array" are not the same thing. The array is the physical storage used by the class. The "list" is the abstract concept that an object of this class type represents.To represent an empty list, for example, set current to 0. Also notice that when an array is member data of a class, it's already in scope for the member functions. So there will be less need to pass the array as a parameter.This doesn't mean you'll never have array parameters, however. Just less frequently Exercises: Try adding the following member functions to the class (for practice). Add in const wherever appropriate: bool Delete(int n); // delete the nth element of the list // return true for success, false if n not a valid position double Sum(); // return the sum of the elements of the list double Average(); // return the average of the elements of the list double Max(); // return the maximum value in the list void Clear(); // reset the list to empty int Greater(double x); // count how many values in the list are greater // than x. Return the count.

Design and declaration of a class

Class: A class in C++ is the building block, that leads to Object-Oriented programming. It is a user-defined data type, which holds its own data members and member functions, which can be accessed and used by creating an instance of that class. A C++ class is like a blueprint for an object. e.g., class ClassName { public: Access specifier; Data members; Member Functions(){} private: };

Delete operator

Deallocates the memory block pointed by ptr (if not null), releasing the storage space previously allocated to it by a call to operator new and rendering that pointer location invalid. delete p;

Overloading operators (including arithmetic operators, logic operators, unary operators, >>, and <<)

Following are the operators that cannot be overloaded pointer to member access operator ( .* ) scope resolution operator ( :: ) member access operator ( . ) condition operator ( ?: ) size operator ( sizeof ) run-time type information operator ( typeid ) Following is the list of overloadable operators CategoryOperators Airthmetic+ , - , * , / , % Bit-wise& , | , ~ , ^ , << , >> Bit-wise assignment&= , |= , ^= , <<== , >>= Relational< , > , == , != , <= , >= Logical|| , && , ! Assignment= Arithmetic assignment-=, += , *= , /= , %= Unary++ , — Subscripting[ ] Deference* Function call( ) Address of& Member access through member pointer->* Member access through object pointer-> Dynamic Allocation and releasenew, delete, new[ ], delete[ ] Comma, Unary Operator Overloading As the name suggests, Unary operators operate on single operand or data. Following are the examples of Unary operators: Unary minus ( - ) operator Logical not ( ! ) operator Decrement ( — ) and Increment ( ++ ) operator

Dynamic array, its declaration, initialization, and deletion

How to use a dynamic array: Define a pointer type. e.g. typedef double* DoubleArrayPtr; declare a pointer type: DoubleArrayPtr a; Call new: a = new double[array size]; Use like an ordinary array: Call to delete: delete [ ] a ;

Basic of inheritance

In C++, it is possible to inherit attributes and methods from one class to another. We group the "inheritance concept" into two categories: derived class (child) - the class that inherits from another class base class (parent) - the class being inherited from To inherit from a class, use the : symbol. In the example below, the Car class (child) inherits the attributes and methods from the Vehicle class (parent):

Use structure as function argument

Like all other types, we can pass structures as arguments to a function. In fact, we can pass, individual members, structure variables, a pointer to structures etc to the function. Similarly, functions can return either an individual member or structures variable or pointer to the structure. e.g., CDAccount shrinkWrap(double theBalance, double theRate, int theTerm) { CDAccount temp; temp.balance = theBalance; temp.interestRate = theRate; temp.term = theTerm; return temp; }

Dereferencing operator (*) and address-of operator (&)

Once a pointer has been assigned the address of a variable, to access the value of the variable, the pointer is dereferenced, using the indirection operator or dereferencing operator *. Consider the following example for better understanding. #include <stdio.h> int main() { int a; a = 10; int *p = &a; // declaring and initializing the pointer //prints the value of 'a' printf("%d\n", *p); printf("%d\n", *&a); //prints the address of 'a' printf("%u\n", &a); printf("%u\n", p); //prints address of 'p' printf("%u\n", &p); return 0; }

Design and declaration of a structure

Structure is a group of variables of different data types represented by a single name. Lets take an example to understand the need of a structure in C programming. We use struct keyword to create a structure in C. The struct keyword is a short form of structured data type. struct struct_name { DataType member1_name; DataType member2_name; DataType member3_name; ... }; How to declare variable of a structure? struct struct_name var_name; or struct struct_name { DataType member1_name; DataType member2_name; DataType member3_name; ... } var_name;

The const modifier (for parameter, for member function)

The const Parameter Modifier Using a call-by-reference parameter is more efficient than using a call-by-value parameter: a call-by-value parameter is initialized to the value of the argument, so time and space are required to copy the argument. a call-by-reference parameter is just another name for the argument, so there is only one copy of the argument. But call by reference enables the changing of the actual parameter. Sometimes it is important to ensure the parameter value cannot be changed by a function. One way to do this is to make the parameter call-by-value then we know it cant be changed. But the other way, still retaining the efficiency of call-by-ref, is to use CONST. If you are using call-by-reference for efficiency, and your function does not change the value of the parameter, use a const modifier so the compiler knows the parameter should not be changed. class Account { public: output(ostream& outs, const Account& myAccount); ... } Using const on member funtions Remember that a member function is invoked from a particular object, a particular instance of the class. When member functions related to a particular object are invoked, it may be useful to know whether invoking a particular member function might change anything about the object. For example, in this reference to the function calculateInterest, do we know whether the method has changed anything about the class? account myAccount; float interest;interest = myAccount.calculateInterest(start_period,end_period);

. Pointer and its declaration

The general syntax of pointer declaration is, datatype *pointer_name; The data type of the pointer and the variable to which the pointer variable is pointing must be the same.

Set and get methods of a class

The meaning of Encapsulation, is to make sure that "sensitive" data is hidden from users. To achieve this, you must declare class variables/attributes as private (cannot be accessed from outside the class). If you want others to read or modify the value of a private member, you can provide public get and set methods. The salary attribute is private, which have restricted access. The public setSalary() method takes a parameter (s) and assigns it to the salary attribute (salary = s). The public getSalary() method returns the value of the private salary attribute. Inside main(), we create an object of the Employee class. Now we can use the setSalary() method to set the value of the private attribute to 50000. Then we call the getSalary() method on the object to return the value.

Keyword typedef and its usage

The typedef keyword allows the programmer to create new names for types such as int or, more commonly in C++, templated types--it literally stands for "type definition". Typedefs can be used both to provide more clarity to your code and to make it easier to make changes to the underlying data types that you use. e.g., Here's how you would declare size_t to be an unsigned integer: typedef unsigned int size_t; In C, struct variables must be declared by a combination of the keyword struct and the name of the struct: struct my_struct_type my_struct_variable; so some programmers use typedef to create shorter names: typedef struct my_struct_type my_short_type_t;

Big Three (destructor, assignment operator, and copy constructor)

What is destructor? Destructor is a member function which destructs or deletes an object. Syntax: ~constructor-name(); Properties of Destructor: Destructor function is automatically invoked when the objects are destroyed. It cannot be declared static or const. The destructor does not have arguments. It has no return type not even void. An object of a class with a Destructor cannot become a member of the union. A destructor should be declared in the public section of the class. The programmer cannot access the address of destructor. The copy assignment operator, often just called the "assignment operator", is a special case of assignment operator where the source (right-hand side) and destination (left-hand side) are of the same class type. It is one of the special member functions, which means that a default version of it is generated automatically by the compiler if the programmer does not declare one. The default version performs a memberwise copy, where each member is copied by its own copy assignment operator (which may also be programmer-declared or compiler-generated). My_Array first; // initialization by default constructor My_Array second(first); // initialization by copy constructor My_Array third = first; // Also initialization by copy constructor second = third; // assignment by copy assignment operator What is a copy constructor? A copy constructor is a member function that initializes an object using another object of the same class. A copy constructor has the following general function prototype: ClassName (const ClassName &old_obj);

Points to remember while using pointers

While declaring/initializing the pointer variable, * indicates that the variable is a pointer. The address of any variable is given by preceding the variable name with Ampersand &. The pointer variable stores the address of a variable. The declaration int *a doesn't mean that a is going to contain an integer value. It means that a is going to contain the address of a variable storing integer value. To access the value of a certain address stored by a pointer variable * is used. Here, the * can be read as 'value at'. Since we have learned the basics of Pointers in C, you can check out some C programs using pointer.


Related study sets

Coursera NN Course2Week1 - Setting up your optimization problem

View Set

Chapter 12: The Arbitration Process

View Set

What is a Relational Database Management System (RDBMS)?

View Set

JKO Emergency Preparedness Response Course (EPRC) - Operator Course

View Set

Lab Safety and Microscope Extra Credit

View Set