0% found this document useful (0 votes)
21 views22 pages

Online CPP Homework Help

Online CPP Homework Help
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views22 pages

Online CPP Homework Help

Online CPP Homework Help
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 22

For any Homework related queries, Call us at : -  

+1 678 648 4277


You can mail us at : - [email protected] or
reach us at : - https://www.cpphomeworkhelp.com/

Problem

Initializer syntax:

Some parts of the initialization of a class should not be performed directly


in code. In particular, when a derived class is instantiated (i.e. when its
constructor is called), the constructors of all its base classes are also
called, but these constructors may require arguments, and the constructors
are called automatically even before the code in the derived constructor is
executed. Similarly, any reference data members must be initialized as
they are created; they cannot be reassigned to point to different data within
the constructor. C++ provides the initializer syntax to allow custom
initialization of constructors and data members:
DerivedClass::DerivedClass() :
BaseClass(someNumber) {

}

This allows calling the base


class constructor with an
argument.
For initializing data members,
the structure of this sort of
statement is as follows:

class_name::class_name(argument_list) :
firstDataMemberToInitialize(initialValue1),
secondDataMemberToInitialize(initialValue
This initialization method – the colon after the constructor arguments,
followed by a comma-separated list of initializations to perform – can be
used for any base class constructor or data member. It can also be used
to call one constructor from another.
To give one more example of the use of this syntax, a colorable Square
class that inherits from a black- and-white Rectangle class might want to
define a constructor like this:

Square::Square(int sideLength, int colorCode) :


Rectangle(sideLength, sideLength),
color(colorCode) {

}

Though some data members can be set directly with assignment


statements within the constructor, base class constructors, data member
constructors, references, and const data members must be initialized with
this syntax.
Problem 1

a. Create a Time class that stores a time as a single number of type


time_t (this is just another name for a certain type of integer). The
constructor should take one argument – the initial value
to set the internally stored time to. This argument should have a
default value of time(0) (the time function is defined in the C++
Standard Library header <ctime>, and the 0 indicates that it should
use the current time). Also create a getter function for the time
stored in Time objects, and a setter function to allow changing the
time the Time object stores later on.

For any Homework related queries, Call us at : -  +1 678 648 4277
You can mail us at : - [email protected] or
reach us at : - https://www.cpphomeworkhelp.com/
b. Rewrite the constructor to use the member initializer syntax instead
of an assignment statement.

Problem 2
Create a class called Complex for performing arithmetic with complex
numbers. Write a program to test your class.
Complex numbers have
the form realPart +
imaginaryPart * i

where i is1 .
Use double variables to represent the private data of the class. Provide a
constructor that enables an object of this class to be initialized when it
is declared. The constructor should contain default values in case no
initial values are provided (a reasonable default number to set a
complex number to is 0  0i ). Provide public member functions that
perform the following tasks:
a. Adding another Complex number: The real parts are added
together and the imaginary parts are added together.
b. Subtracting another Complex number: The real part of the right
operand is subtracted from the real part of the left operand, and
the imaginary part of the right operand is subtracted from the
imaginary part of the left operand.
c. Multiply by another Complex number: The product of the
imaginary parts is subtracted from the product of the real parts to
get the new real part, and the products of the imaginary and real
and real and imaginary parts are added to form the new imaginary
part.

For any Homework related queries, Call us at : -  +1 678 648 4277
You can mail us at : - [email protected] or
reach us at : - https://www.cpphomeworkhelp.com/
c.Print Complex numbers in the form (a, b), where a is the real part
and b is the imaginary part. The member functions should each return
another Complex object, and should be called with a syntax
like complex1.add(complex2);.

friend Functions and friend Classes:


A friend function of a class is defined outside that class's scope, yet has
the right to access the non- public (and public) members of the class.
Standalone functions or entire classes may be declared to be friends of
another class.
If, for example, we wanted to declare a class to represent a person and a
class to represent a dog, but we wanted to allow any object of the Person
class to access any private data or functions of Dog objects, we might
declare:
class Dog {
friend class Person;

};

If we only want to allow the Person’s Walk function to access private


members Dog class, and we’ve already declared the Person class (or
have placed the declaration class Person;) earlier in the file,

we could specify:
class Dog {
friend void Person::Walk();

For any Homework related queries, Call us at : -  +1 678 648 4277
You can mail us at : - [email protected] or
reach us at : - https://www.cpphomeworkhelp.com/

};

Static Class Members:


There is an important exception to the rule that each object of a class has
its own copy of all the data members of the class. In certain cases, only
one copy of a variable should be shared by all objects of a class. A static
data member is used for these and other reasons.

The declaration of a static member begins with the static keyword.


Although they may seem like global variables, a class’s static data
members have class scope. Also, static members can be declared public,
private or protected.
Member functions can also be declared static, meaning that no instance of
a class is needed to access them. For instance, if we had a
MartianInvader class which stored a class-wide static variable
martianCount, we might define a static function getMartianCount as
follows:
static const int getMartianCount() { return martianCount; }

Any static class member can be accessed from within a class function.
Additionally, any public class member can be accessed either via an
object of the class or via the class name; the two definitions of count
below are equivalent:
MartianInvader myMartian;
int count = myMartian.getMartianCount();
int count = MartianInvader::getMartianCount(); //Use scope resolution
operator (::)

Static member functions cannot access or modify non-static member data.

For any Homework related queries, Call us at : -  +1 678 648 4277
You can mail us at : - [email protected] or
reach us at : - https://www.cpphomeworkhelp.com/
Constant Member Functions:

Declaring a member function with the const keyword specifies that


the function is a “read-only” function that does not modify the
object on which it is called.

To declare a constant member function, place the const keyword after


the closing parenthesis of the argument list. The const keyword is
required in both the declaration and the definition. A constant
member function cannot modify any data members or call any
member functions that aren't also declared const.

const int Date::getMonth() const


{
return month; // Doesn't modify anything; trying to modify a data
member
} // from here would be a syntax error

If an object of class Date would be declared as const Date


tomorrow;, no non-const member functions could be called on it.
Problem 3

Find the errors in the following class and explain how to correct
them.

class
StockPurchase {
public:
StockPurch
ase(const
double
newPrice) {
//
When
someo
For any Homework related queries, Call us at : -  +1 678 648 4277
ne You can mail us at : - [email protected] or
buys a reach us at : - https://www.cpphomeworkhelp.com/
previousDefaultPrice = defaultPrice;
currentPrice = newPrice;
defaultPrice =
previousDefaultPrice
+ (currentPrice - previousDefaultPrice) / 2.0;
timeLastChecked = time(0); // record the current
timestamp
}

static const double getDefaultPrice()


{ return previousDefaultPrice
+ (currentPrice -
previousDefaultPrice) / 2.0;
}

// Returns the current time, updating the


timestamp to show
// that this object was read recently
const double getCurrentPrice() const
{
timeLastChecked =
time(0); return
currentprice;
}

private:
double previousDefaultPrice,
currentPrice; static double defaultPrice;
time_t timeLastChecked; // A time_t is
basically just an integer
}

Problem 4

For any Homework related queries, Call us at : -  +1 678 648 4277
You can mail us at : - [email protected] or
reach us at : - https://www.cpphomeworkhelp.com/
Fill in the blanks in each of the following statements (you may wish to
refer to the chart on Page 15 of the lecture notes):

1. A base class’s members can be accessed only in the base-


class definition or in derived-class definitions.

2. A base class’s members are accessible within that base class


and anywhere that the program has a handle to an object of that
base class or to an object of one of its derived classes.

3. A base class’s protected access members have a level of protection


between those of public and
access.

4. When deriving a class from a base class with public inheritance,


public members of the base class become _ members of the
derived class, and protected members of the base class become _
members of the derived class.

5. When deriving a class from a base class with protected inheritance,


public members of the base class become _ members of the
derived class, and protected members of the base class become _
members of the derived class.

Problem 5
Create an inheritance hierarchy containing base class Account and
derived classes SavingsAccount and CheckingAccount that inherit
from class Account. Make sure all return values, arguments, and
member functions are declared const where appropriate.

For any Homework related queries, Call us at : -  +1 678 648 4277
You can mail us at : - [email protected] or
reach us at : - https://www.cpphomeworkhelp.com/
a. Base class Account should include one data member of type double to
represent the account balance. The class should provide a constructor
that receives an initial balance and uses it to initialize the data
member. The constructor should validate the initial balance to ensure
that it is greater than or equal to 0.0. If not, the balance should be set
to 0.0 and the constructor should display an error message, indicating
that the initial balance was invalid. (You may wish to use the cerr
object, which functions just like cout except that it outputs to the
standard error output rather than standard text output. Usually, but not
always, the two are functionally similar.)

The class should provide four member functions. Member function


Credit should add an amount to the current balance. Member function
Debit should withdraw money from the Account and ensure that the
debit amount does not exceed the Account's balance. If it does, the
balance should be left unchanged and the function should print the
message "Debit amount exceeded account balance." Member function
getBalance should return the current balance.

b. Derived class SavingsAccount should inherit the functionality of an


Account, but also include a data member of type double indicating
the yearly interest rate (percentage) assigned to the Account.
SavingsAccount's constructor should receive the initial balance, as
well as an initial value for the SavingsAccount's interest rate. (Make
sure to call the base class constructor appropriately.)
SavingsAccount should provide a public member function
calculateInterest that returns a double indicating the amount of
interest earned by an account. Member function calculateInterest
should take one integer argument indicating the number of years gone
by, and should determine the interest amount by the

For any Homework related queries, Call us at : -  +1 678 648 4277
You can mail us at : - [email protected] or
reach us at : - https://www.cpphomeworkhelp.com/
formula I  B * (1  r)t , where I is the interest, B is the initial
balance, r is the interest rate, and t is the number of years gone by.
[Note: SavingsAccount should inherit member functions credit and
debit as is without redefining them.]

c. Derived class CheckingAccount should inherit from base class


Account and include an additional data member of type double that
represents the fee charged per transaction. CheckingAccount's
constructor should receive the initial balance, as well as a parameter
indicating a fee amount. Class CheckingAccount should redefine
member functions Credit and Debit so that they subtract the fee from
the account balance whenever either transaction is performed
successfully. CheckingAccount's versions of these functions should
invoke the base- class Account version to perform the updates to an
account balance. CheckingAccount's debit function should charge a
fee only if money is actually withdrawn (i.e., if the debit amount does
not exceed the account balance).

[Hint: Define Account's Debit function so that it returns a bool


indicating whether money was withdrawn. Then use the return value
in the CheckingAccount version of the function to determine
whether a fee should be charged.]
Write a program that creates objects of each class and tests their
member functions. Add interest to the SavingsAccount object by first
invoking its calculateInterest function, then passing the returned
interest amount to the object's Credit function.
Classes and header files:
Usually a class is defined in two separate files: a header file and an
implementation file. If you are
defining a class SomeClass, typically you would put the class
declaration (class SomeClass {…};) in a SomeClass.h file with
function prototypes only, and then give all

For any Homework related queries, Call us at : -  +1 678 648 4277
You can mail us at : - [email protected] or
reach us at : - https://www.cpphomeworkhelp.com/
the function definitions in a SomeClass.cpp file (which includes
SomeClass.h). The major exception to this is functions that are just one
statement, such as getter and setter functions, which are usually small
enough to fit into the header file.

This makes for a modular program setup: main is in some file like
main.cpp, and SomeClass is defined in SomeClass.h and SomeClass.cpp.
You must then compile both main.cpp and SomeClass.cpp and link them
together to get the final executable.
Problem 6
Define an Array class that expands the functionality of C++ arrays. Show
how you would split your definition into an Array.h file and an Array.cpp
file.
The class should contain one data member that is a pointer to a dynamically
allocated array of integers, and an integer that stores the current size of the
array. The size integer should be const – it should not be changeable after
the class constructor is called.
The class should have 3 constructors: one that takes just a number of
elements to allocate (initializing them all to 0), another that takes a
number of elements and an array of initial elements, and a copy
constructor that allocates a new array of the same size as the Array that is
being copied, and then copies the elements one by one.

Define 4 member functions: getLength to return the number of elements in


the Array; getElement to take an integer n and return a modifiable
reference to the (n+1)th element of the array; another getElement function
that is declared const and returns a non-modifiable reference; and a print
function that takes a separator string and prints the elements one by one
separated by the separator string. (For instance, myArray.print("\n") should
print the array elements with newlines between each pair.)

For any Homework related queries, Call us at : -  +1 678 648 4277
You can mail us at : - [email protected] or
reach us at : - https://www.cpphomeworkhelp.com/
Also define a destructor to deallocate the memory that was allocated to the
internal array when the
Array object is destroyed.
You do not need to define a main function that actually uses this class, but it
will presumably be useful for testing purposes to try creating a few Array
objects and manipulating them.

For any Homework related queries, Call us at : -  +1 678 648 4277
You can mail us at : - [email protected] or
reach us at : - https://www.cpphomeworkhelp.com/
Solution
Problem 1

(a)
#include
<ctime>

class Time
{ // or long, or
time_t t; int
public:
Time( long initialTime = time(0) )
{
t = initialTime;
}
long getTime()
{
return t;
};
void setTime(long newTime)
{
t = newTime;
}; // or long, or int
};

(b)
#include <ctime>

class Time
{
time_t t; public:

For any Homework related queries, Call us at : -  +1 678 648 4277
You can mail us at : - [email protected] or
reach us at : - https://www.cpphomeworkhelp.com/
Time(time_t initialTime = time(0) ) : t(initialTime) {}
int getTime()
{
return t;
}

void setTime(time_t newTime)


{
t= newTime;

}
};

Problem 2

#inclu
de
<iostre
am>
using
names
pace
std;
class
Compl
ex
{
double
real,
imagina
ry;
public:
Complex(double realPart=0, double imagPart=0)
{real=realPart; imaginary=imagPart;}; double
getReal()

For any Homework related queries, Call us at : -  +1 678 648 4277
You can mail us at : - [email protected] or
reach us at : - https://www.cpphomeworkhelp.com/
{
return real;
};
double getImaginary()
{

return imaginary;
};
void set(double realPart, double imagPart)
{
real = realPart;
imaginary =
imagPart;
};
Complex
add(const
Complex &obj)
const
{
return
Complex(real
+ obj.real,
imaginary +
obj.imaginary
);
};
Complex
subtract(const
Complex &obj)
const
{
return
Complex(real
- obj.real,
imaginary -
obj.imaginary
For any Homework related queries, Call us at : -  +1 678 648 4277
); You can mail us at : - [email protected] or
}; reach us at : - https://www.cpphomeworkhelp.com/
};
};

Problem 3 (UNGRADED)

Error 1: The first occurs in function getIncrementedData. The


function is declared const, but it modifies the object.

Correction: To correct the first error, remove the const keyword


from the definition of getIncrementedData.

Error 2: The second error occurs in function getCount. This function


is declared static, so it is not allowed to access any non-static
member of the class.
Correction: To correct the second error, remove the output line from
the getCount definition.

Problem 4

1.A base class’s protected members can be accessed only in the


base-class definition or in derived-class definitions.

1.A base class’s public members are accessible within that base class
and anywhere that the program has a handle to an object of that base
class or to an object of one of its derived classes.

2.A base class’s protected access members have a level of protection


between those of public and
private access.

For any Homework related queries, Call us at : -  +1 678 648 4277
You can mail us at : - [email protected] or
reach us at : - https://www.cpphomeworkhelp.com/
4.When deriving a class from a base class with public inheritance, public
members of the base class become public members of the derived class,
and protected members of the base
class become protected members of the derived class.

5.When deriving a class from a base class with protected inheritance,


public members of the base
class become protected members of the derived class, and protected
members of the base class become protected members of the derived
class.

Problem 5

#include <iostream>
#include <cmath> using
namespace std;

class Account //part A


{
double balance;
public:
Account(double
initBalance);
void Credit(double
amountToCredit); bool
Debit(double amountToDebit);
double getBalance();
};
Account::Account(double
initBalance):balance(initBalance)
{
if(balance<0.0)
{ For any Homework related queries, Call us at : -  +1 678 648 4277
You can mail us at : - [email protected] or
reach us at : - https://www.cpphomeworkhelp.com/
balance=0.0;
cerr << "Invalid balance, must be non-
negative"<<endl// or cout
<< "Setting balance to zero"<<endl;
}
}

double Account::Credit(double
amountToCredit)
{
balance +=
amountToCredit;
return balance;
}

bool
Account::Debit(dou
ble amountToDebit)
{
if(balance >=
amountToDebit)
{
balance -=
amountToDebit;
return true;
}
else
{
cerr << "Debit amount exceeded
account balance."<<endl; return false;
}
}

For any Homework related queries, Call us at : -  +1 678 648 4277
You can mail us at : - [email protected] or
reach us at : - https://www.cpphomeworkhelp.com/
Account::Account(double
initBalance):balance(initBalance)
{
if(balance<0.0)
{

SavingsAccount::SavingsAccount(double
interestRate, double initBalance)
: Account(initBalance)
{
interestRate=interestRate;
}

double SavingsAccount::calculateInterest(int years)


{
return balance * pow(1+interestRate, years);
}

class CheckingAccount: public Account //part C


{
double
fee;
public:
CheckingAccount(double
transactionFee, double initBalance);
void Credit(double amountToCredit);
bool Debit(double amountToDebit);
};

For any Homework related queries, Call us at : -  +1 678 648 4277
You can mail us at : - [email protected] or
reach us at : - https://www.cpphomeworkhelp.com/
CheckingAccount::CheckingAccount(double transactionFee, double
initBalance)
: Account(initBalance)
{
fee = transactionFee;
}

void CheckingAccount::Credit(double amountToCredit)


{
Account::Credit( amountToCredit - fee );
}

bool CheckingAccount::Debit(double amountToDebit)


{
return Account::Debit(amountToDebit + fee);
}
Problem 6 Array.h

#include <iostream> #include


<string> using namespace std;
class Array
{
const int size;
int
*internalArra
y; public:
Array(int
numElemen
ts);

For any Homework related queries, Call us at : -  +1 678 648 4277
You can mail us at : - [email protected] or
reach us at : - https://www.cpphomeworkhelp.com/
Array(int[] initialValues, int
numElements); Array(const Array &);
int getLength() { return size; }
int &getElement(const int);
const int &getElement(const int)
const; void print(const string
&separator);
~Array();
};
Array.cpp

#include
<iostream>
#include
<string>
#include
"Array.h" using
namespace std;

Array::Array(int
numElements) :
size(numElemen
ts)
{
internalArray = new
int[size]; for(int i = 0; i
< size; i++)
internalArray[i] =
0;
}

Array::Array(int
initialValues[], int
numElements) :
size(numElements)
For any Homework related queries, Call us at : -  +1 678 648 4277
{ You can mail us at : - [email protected] or
reach us at : - https://www.cpphomeworkhelp.com/
Array(int[] initialValues, int
numElements); Array(const Array
&);
int getLength() { return
size; } int
&getElement(const int);
const int &getElement(const int)
const; void print(const string
&separator);
~Array();
};

{
return internalArray[n];
}

void Array::print(const string


&separator)
{
cout <<
internalArray[0];
for(int i=1; i<size;
i++)
cout <<
separator <<
internalArray[i]
;
}

Array::~Array()
{
delete[]
internalArray;
};
For any Homework related queries, Call us at : -  +1 678 648 4277
You can mail us at : - [email protected] or
reach us at : - https://www.cpphomeworkhelp.com/

You might also like