Skip to content

Instantly share code, notes, and snippets.

@imduffy15
Last active December 17, 2015 14:49
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save imduffy15/5626891 to your computer and use it in GitHub Desktop.
Save imduffy15/5626891 to your computer and use it in GitHub Desktop.

2012

Question 1

Part A

#include <iostream>

using namespace std;

int main() {
	char c = 'T';
	char d = 'S';
	
	char *p1 = &c;
	char *p2 = &d;
	char *p3;
	
	// *p3 results in S
	p3 = &d;
	cout << "*p3 = " << *p3 << endl;
	
	// *p results in T, p3 results in 6940
	p3 = p1;
	cout << "*p3 = " << *p3 << ", p3 = " << p3 << endl; 
	
	// *p1 results in S p1 results in 9772
	*p1 = *p2;
	cout << "*p1 " << *p1 << ", p1 = " << p1 << endl;
	
	return 0;
}

Part B

Method 1:

#include <iostream>
using namespace std;

int main() {
	cout << "Hello World" << endl;
}

Method 2:

#include <iostream>
using std:cout;
using std:endl;

int main() {
	cout << "Hello World" << endl;
}

Method 3:

#include <iostream>

int main() {
	std::cout << "Hello World" << std::endl;
}

Part C

Constructors and destructors are fundamental to the concept of classes in C++. Both constructor and destructor are more or less like normal functions that are provided to enhance the capabilitites of a class.

Constructor, as the name suggests is used to allocate memory and constructor the object of a class while destructor is used to do the required clean-up when a class object is destroyed.

Part D

void cube(float &n)

The above line of code is known as a function protocol. It defines the function cube. From this we can see that cube doesn't return anything and it takes a reference to a float.

Since this is passed by reference n will refer to some variable instead of copying the contents of n and modifying it.

Part E

A function should be made private when you don't need other objects or classes to acces the function.

Part F

False.

The function will be able to modify the variable of the call by reference and will be able to return something.

Part G

In some programs, it is not possible to know which function will be called until runtime. This is known as late binding. In C++, one way to get late binding is to use the function pointers.

Example:

#include <iostream>

int add(int x, int y) {
	return x+y;
}

int main() {
	int (*functionPointer)(int,int) = add;
	std::cout << functionPointer(1,2) << "\n";
}

Part H

The members and base classes of a struct are public by default, while in a class, they default to private.

struct and class are otherwise functionally equivalent.

Part I

class Money {
	public:
		Money();
	
		int getCents() const;
		int getEuro() const;
		
		bool operator ==(const Money& amount1, const Money& amount2);
	private:
		int euro;
		int cents;
}

Question 2

Part A

Inheritance suggests an object is able to inherit characteristics from another object. In more concrete terms, an object is able to pass on its state and behavior to its children. For inheritance to work the objects need to ave characteristics in common with each other.

Interitance devlopes a is-a relationship between objects.

Example: A shape is an object with virtual functions area, parameter. Circle has a radius and is a shape. Rectangle has a height and width and is a shape. Square is a rectangle with some constrant on height and width.

Public - Everything which is aware of the class is aware that it contains these variables/functions

Protected - Only children, and their children are aware that the class contain these variables/functions

Privte - Nobody but the class itself is aware of these variables/functions.

class Shape {
	public:
		virtual void getArea() = 0;
		virtual void getPerimeter() = 0;
}

class Rectangle : public Shape {
	protected:
		int height, width;

	public:
		Rectangle(int height, int width);
}

class Square : public Rectangle {
	public:
		Square(int height, int width);
}

class Circle : public Shape {
	public:
		Circle(int radius);
	private:
	int radius;
}

Part B

No. C++ will supply a default copy constructor and assignment operator.

The assignment operator will do member-wise assignment e.g.

MyClass& myClass::operator=(const MyClass& rhs) {
	x = other.x;
	c = other.c;
	s = other.s;
	return this;
}

The copy constructor will member-wise copy e.g.

Myclass:MyClass(const Myclass& other) :
	x(other.x), c(other.c), s(other.s)
{}

Part C

An abstract class is a classed that is designed to be specifically used as a base class. An abstract class contains at least one pure virtual function.

Pure virtual functions have no body at all! A pure virtual function simply acts as a placeholder that has to be redefined by the derived classes.

#include <iostream>

using namespace std;

class Shape {
	protected:
		double area, perimeter;
	public:
		virtual void display() = 0;
};

class Rectangle : public Shape {
	private:
		int height, width;
	public:
		Rectangle();
		Rectangle(int height, int width);
		void display();
};

Rectangle::Rectangle() {
	//Empty Constructor
}

Rectangle::Rectangle(int height, int width) {
	this->height = height;
	this->width = width;
	this->area = height * width;
	this->perimeter = height+height+width+width;
}

void Rectangle::display() {
	cout << "Height: " << this->height << "\n"
		 << "Width: " << this->width << "\n"
		 << "Area: " << this->area << "\n"
		 << "Perimeter: " << this->perimeter << "\n";
}

int main() {
	Rectangle rec = Rectangle(10,10);
	rec.display();
	return 0;
}

Question 3

Part A

Part 1

A stream is simply a continuous flow or succession of data. Streams are used to assure a good and secure flow of data between an application and files.

cin - input stream, connected to the keyboard.

cin >> data; // Take some input from the keyboard and place it into data.

cout - output stream, connected to the screen.

cout << data; // Display data on the screen

Part 2

#include <iostream>
#include <iomanip>

using namespace std;

int main() {
	cout << setiosflags(ios::fixed)
	<< setiosflags(ios::showpoint)
	<< setprecision(2) 
	<< 100.500000;
	return 0;
}

Part 3

#include <fstream>

using namespace std;

int main() {
	ofstream outStream;
	outStream.open("myfile.dat", ios::app);
	outStream << "Hello world";
	outStream.close();
	return 0;
}

Part B

Part 1

  1. C++ supports pointers where as Java does not.
  2. At complile time java source code converts into byte code. The interpreter executes this byte code at run time and gives an output. Java is interpreted for the most part hence platform independent. C++ source code is converted to machine code on compile which makes it platform dependant.
  3. C++ supports operator overloading and multiple inheritance, java does not.
  4. Everything is an object in java. There a single root hierarchy.
  5. Java does not support default arguments like C++
  6. There is no scope resolution operator in java.
  7. Java is Pass-by-value
  8. Java does not support unsigned integer.

Part 2

Exceptions provide a way to react to exceptional circumstances (like runtime errors) in our program by transferring control to special functions called handlers.

#include <iostream>

using namespace std;

int main() {
	try {
		throw 10;
	} catch(int e) {
		cout << "Exception occured: " << e << endl;
	}
	return 0;
}

2011

Question 1

Part A

Skip

Part B

Skip

Part C

Mutator - Provide a way to change private variables.

Accessor - Provide a way to access private variables.

Part D

Assuming input() plans to set/change some member variables const will prevent this.

const forbids a method to change class member variables.

Part E

Shallow copy - Some members of the copy may reference the same object as the original.

Deep Copy - All members of the original are cloned.

Part F

The destructor is called when delete is used and when the local ojbject goes out of scope.

Part G

void g();

Part H

The dot operator is used to access member variables of an object. The scope resolution operator is used to access members of a namespace or class.

Part I

class Money {
	public:
		Money();
	
		int getCents() const;
		int getEuro() const;
		
		bool operator ==(const Money& amount1, const Money& amount2);
	private:
		int euro;
		int cents;
};

Money::operator==(const Money& amount1, const Money& amount2) {
	return(amount1.euro == amount2.euro && amount1.cents == amount2.cents);
}

Question 2

Part A

is a relationships relate to the inheritance. has a relates to member variables.

Below dog is a animal and has a name.

class Animal {

};

class Dog : public Animal {
	std:string name;
};

Part B

If a member variable or function in some base class is marked as protected this means that child classes can access that variable or function.

All places have a name, beach is a place.

class Place {
	protected:
		std::string name;
}

class Beach : public Place {

}

Part C

#include <iostream>

using namespace std;

class Account {
	private:
		static int nextAccountNumber;
		string owner;
		float balance;
		int accountNumber;
	
	public:
		Account();
		Account(string owner, float balance);
		virtual void display();
};

class DepositAccount : public Account {
	private:
		float interestRate;
	
	public:
		DepositAccount();
		DepositAccount(string owner, float balance, float interestRate);
		virtual void display();
};

int Account::nextAccountNumber = 0;

Account::Account() {
	//empty constructor
}

Account::Account(string owner, float balance) { 
	this->owner = owner;
	this->balance = balance;
	this->accountNumber = this->nextAccountNumber++;
}

void Account::display() {
	cout << "Account Number: " << this->accountNumber << "\n"; 
	cout << "Owner: " << this->owner << "\n";
	cout << "balance: " << this->balance << "\n";
}

DepositAccount::DepositAccount() {
	//empty constructor
}

DepositAccount::DepositAccount(string owner, float balance, float interestRate)
	: Account(owner,balance) {
		this->interestRate = interestRate;
}

void DepositAccount::display() {
	Account::display();
	cout << "Interest rate:" << this->interestRate << "\n";
}

int main() {
	DepositAccount dep0 = DepositAccount("Tom Jones",1231.10,0.05);
	dep0.display();
	cout << "\n";
	
	DepositAccount dep1 = DepositAccount("Bill Hackett",50102.10,0.05);
	dep1.display();
	cout << "\n";
	
	DepositAccount dep2 = DepositAccount("Jim Doyle",4131.10,0.05);
	dep2.display();
	cout << "\n";
	
	DepositAccount dep3 = DepositAccount("Mark Johnston",6012.10,0.05);
	dep3.display();
	cout << "\n";
	
	DepositAccount dep4 = DepositAccount("Simon Clark",9681.10,0.05);
	dep4.display();
	cout << "\n";
	
	return 0;
}

Question 3

Part A

During program execution, each process is located somewhere in an area of memory. The location of an object in memory is called its address. In C++ there is an address operator, &, which allows you to obtain the object's address.

The value returned by this address operators indicates the location of an object in memory. emory locations are determined by the operating system and it is possible that objects addresses may be different during repeated runs of a program.

C++ offers two mechanisms for dealing with addresses, references and pointers. Pointers are an older mechanism that C++ inerited from C, while references are a new mechanism that originated in C++.

A pointer is a variable that holds a memory address.

Part B

The new operator provides dynamic storage allocation.

The new operator returns a memory location of the object that was just created.

Should it of failed to create it two things could happen.

  1. A null pointer is returned.
  2. A bad_alloc exception is thrown.

Part C

Templates are the foundation of generic programming which involves writing code in a way that is independent of any particular type.

A template is a blueprint or formula for creating a generic class or a function. The library containers like iterators, and algorithms are examples of generic programming and have been developed using template concept.

Tthere is a single defination of each container, such as vector, but we can define many different kinds of vectors, for example, vector<int> or vector<string>

Strategies for writing and testing a template:

  • Develop function normally, using actual data types.
  • Completely debug/test "ordinary" function
  • Convert to template, replace type names with type parameter as needed

Advantages of templates include:

  • Reducing the repetition of code
  • Static polymorphism
  • Policy based design

Part D

#include <iostream>

using namespace std;

template <typename T> T minimum(T obj1, T obj2);

int main() {
	cout << minimum(10,12);
}

template <typename T> T minimum(T obj1, T obj2) {
	if(obj1 > obj2) {
		return obj1;
	} else {
		return obj2;
	}
}

2011 Repeat

Question 1

Part A

Skip

Part B

A typedef declaration lets you define your own identifiers that can be used in place of type speciiers such as int, float and double. A typedef declaration does not reverse storage. The names you define using typedef are not new data types, but synonyms for the data types or combinations of data types they represent.

Part C

Seperating the interface from implementation allows for cleaner and easy to maintain code. In a company like environment interfaces allow the company to set out restrictions with interfaces. Along with this they are able to inform other members of the project about implementations that don't yet exist but soon will.

Part D

The following line sets up an if condition. It says only load the implementation if filename_h is not defined. This prevents the header file form being loaded multiple times.

Part E

The following line of code means all publicly accessible variabls in Vehicle get converted to protected within the car class.

Part F

char input[20];

Part G

class Figure {
public:
	virtual void draw() = 0;
}

Part H

A namespace can define its own members within itself or externauly using explicit qualification. The following is an example:

namespace A {
	void b() { }
}

Within namespace A member void b is defined internally.

Part I

#include <iostream>

using namespace std;

int main() {
	bool isPalindrome=true;
	char* input;
	
	cin >> (input = new char);
	
	int length = strlen(input);
	
	for(int i=0;i<length/2;i++) {
		if(input[i] != input[length-1-i]) {
			isPalindrome = false;
		}
	}
	
	if(isPalindrome) cout << "This string is a palindrome\n";
	else cout << "this string is not a palindrome\n";
	
	return 0;
}

Question 2

Part A

Part 1

  • Data hiding is also known as Encapsulation.
  • Encapsulation is the process of combining data and functions into a single unit called class.
  • Data hiding is the mechanism where the details of the class are hidden from the user.
  • The user can perform only a restricted set of operations in the hidden member class.
  • Encapsulation is a powerful feature that leads to information hiding, abstract data type and friend funtion.
  • Using the method of encapsulation the programmer cannot directly access the class.
class Person {
private:
	int age;
	string name;
public:
	Person(int age, int name);
	int getAge();
	string getName();
}

In the following both age and name are set to private, this means only this class can access them.

They are set by the Person constructor and can be read using the given accessors getAge and getName.

Part 2

A virtual function is a function whose behaviour can be overriden within an inheriting class by a function with the same signature.

Polymorphism is a mechanism that allows you to implement a function in different ways.

In some programs, it is not possible to know which function will be called until runtime. This is known as late binding. One way to get late binding is to use function pointers.

Polymorphism can be achieved by either using virtual functions or late bindings.

#include <iostream>

using namespace std;

class ClassA {
public:
	virtual void display();
	ClassA();
};

void ClassA::display() {
	cout << "ClassA\n";
}

ClassA::ClassA() { }

class ClassB : public ClassA {
public:
	virtual void display();
	ClassB();
};

ClassB::ClassB() { }

void ClassB::display() {
	cout << "ClassB\n";
}

int addition(int a, int b) {
	return a+b;
}

int substraction(int a, int b) {
	return a-b;
}

int main() {
	// Example of Polymorphism via virtual functions
	ClassA classA = ClassA();
	classA.display();
	
	ClassB classB = ClassB();
	classB.display();
	
	// Example of Polymorphism with late bindings
	string operation = "+";
	int (*operationPointer)(int a, int b);
	
	if(operation == "+") {
		operationPointer = addition;
	} else {
		operationPointer = substraction;
	}
	
	cout << operationPointer(10,10) << "\n";
	
	return 0;
}

Part B

#include <iostream>

using namespace std;

class Shape {
protected:
  float area;
	float perimeter;
public:
	virtual void display();
	virtual string getShapeName() = 0;
};

class Rectangle : public Shape {
public:
	Rectangle(float width, float height);
	virtual string getShapeName();
};

class Circle : public Shape {
public:
	Circle(float radius);
	virtual string getShapeName();
};

// Part 1

void Shape::display() {
	cout << "Shape: " << getShapeName() << "\n"
		 << "Area: " << this->area << "\n"
		 << "Perimeter: " << this->perimeter << "\n";
}

Rectangle::Rectangle(float width, float height) {
	this->area = width*height;
	this->perimeter = width+width+height+height;
}

string Rectangle::getShapeName() {
	return "Rectangle";
}

Circle::Circle(float radius) {
	this->area = 3.14 * radius * radius;
	this->perimeter = 2 * 3.14 * radius;
}

string Circle::getShapeName() {
	return "Circle";
}

// Part 2

int main() {
	Rectangle rec = Rectangle(4,10);
	rec.display();
	
	cout << "\n";
	
	Circle cir = Circle(10);
	cir.display();
	
	return 0;
}

Question 3

Part A

p1 = p2

Make p1 point to the same place as p2.

*p1 = *p2

Put the value stored at *p2 into *p1.

Part B

Call by value means passing the value directly to a function. The called function uses the value in a local variable. Any changes to it do not affect the source variable.

Call by reference means passing the address of a variable where the actual value is stored. The called function uses the value stored in the passed address. Any changes to it do affect the source variable.

The issue with using call by value for large data would be that it would be copied, and hence take up double the memory.

You could use call by reference and mark it as const so the function is unable to modify it.

Part C

Skip.

A friend function that is a "friend" of a given class is allowed access to public, private, or protected data in that class. Normally a function that is defined outside of a class cannot access such information. Declaring a function a friend of a class allows this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment