SlideShare a Scribd company logo
For any Homework related queries, Call us at : - +1 678 648 4277
You can mail us at :- info@cpphomeworkhelp.com or
reach us at :- https://www.cpphomeworkhelp.com/
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(initialValue2) {
…
}
cpphomeworkhelp.com
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 Rectangleclass 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 Timeclass 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 timefunction 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 Timeobject
stores later on.
cpphomeworkhelp.com
Create a class called Complexfor 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.
b. Rewrite the constructor to use the member initializer syntax instead of an assignment
statement.
Problem 2
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();
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 getMartianCountas 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.
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:
StockPurchase(const double newPrice) {
// When someone buys a stock, modify the default price
// according to how much they were willing to pay
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
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.
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
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 Creditfunction.
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
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.)
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 Arrayobjects and manipulating them.
cpphomeworkhelp.com
Problem 1
(a)
#include <ctime>
class Time
{
time_t t;
public:
// or long, or int
Time( long initialTime = time(0) )
{
t = initialTime;
}
long getTime()
{
return t;
};
void setTime(long newTime)
{
t = newTime;
};
};
(b)
#include <ctime>
// or long, or int
cpphomeworkhelp.com
Time(time_t initialTime = time(0) ) : t(initialTime) {} int getTime()
{
return t;
}
void setTime(time_t newTime)
{
t= newTime;
}
};
Problem 2
#include <iostream>
using namespace std;
class Complex
{
double real, imaginary;
public:
Complex(double realPart=0, double imagPart=0) {real=realPart;
imaginary=imagPart;}; double getReal()
class Time
{
time_t t; public:
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 );
};
Complex multiply(const Complex &obj) const
{
return Complex(real * obj.real - imaginary * obj.imaginary,
real * obj.imaginary + imaginary * obj.real);
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.
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)
{
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(double amountToDebit)
{
if(balance >= amountToDebit)
{
balance -= amountToDebit;
return true;
}
else
{
cerr << "Debit amount exceeded account
balance."<<endl; return false;
}
}
cpphomeworkhelp.com
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);
};
Account::Account(double
initBalance):balance(initBalance)
{
if(balance<0.0)
{
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 *internalArray;
public:
Array(int numElements);
cpphomeworkhelp.com
Array.cpp
#include <iostream> #include
<string> #include "Array.h" using
namespace std;
Array::Array(int numElements) : size(numElements)
{
internalArray = new int[size]; for(int i = 0; i
< size; i++)
internalArray[i] = 0;
}
Array::Array(int initialValues[], int numElements) : size(numElements)
{
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();
};
cpphomeworkhelp.com
{
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;
};
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();
};
cpphomeworkhelp.com

More Related Content

Similar to Online CPP Homework Help

C++ Object oriented concepts & programming
C++ Object oriented concepts & programmingC++ Object oriented concepts & programming
C++ Object oriented concepts & programming
nirajmandaliya
 
While writing program in any language, you need to use various variables to s...
While writing program in any language, you need to use various variables to s...While writing program in any language, you need to use various variables to s...
While writing program in any language, you need to use various variables to s...
bhargavi804095
 
11-Classes.ppt
11-Classes.ppt11-Classes.ppt
11-Classes.ppt
basavaraj852759
 
Object oriented design
Object oriented designObject oriented design
Object oriented designlykado0dles
 
Intake 37 4
Intake 37 4Intake 37 4
Intake 37 4
Mahmoud Ouf
 
Intake 38 3
Intake 38 3Intake 38 3
Intake 38 3
Mahmoud Ouf
 
Java căn bản - Chapter7
Java căn bản - Chapter7Java căn bản - Chapter7
Java căn bản - Chapter7Vince Vo
 
Chapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part IIChapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part II
Eduardo Bergavera
 
C++ beginner's guide ch08
C++ beginner's guide ch08C++ beginner's guide ch08
C++ beginner's guide ch08Jotham Gadot
 
Presentation 3rd
Presentation 3rdPresentation 3rd
Presentation 3rdConnex
 
Lecture 4. mte 407
Lecture 4. mte 407Lecture 4. mte 407
Lecture 4. mte 407
rumanatasnim415
 
Classes-and-Objects-in-C++.pdf
Classes-and-Objects-in-C++.pdfClasses-and-Objects-in-C++.pdf
Classes-and-Objects-in-C++.pdf
ismartshanker1
 
C# classes objects
C#  classes objectsC#  classes objects
C# classes objects
Dr.Neeraj Kumar Pandey
 
Unit vi(dsc++)
Unit vi(dsc++)Unit vi(dsc++)
Unit vi(dsc++)
Durga Devi
 
Lecture 9
Lecture 9Lecture 9
Lecture 9
Mohammed Saleh
 
Introduction to Python - Part Three
Introduction to Python - Part ThreeIntroduction to Python - Part Three
Introduction to Python - Part Three
amiable_indian
 
Static Keyword Static is a keyword in C++ used to give special chara.pdf
  Static Keyword Static is a keyword in C++ used to give special chara.pdf  Static Keyword Static is a keyword in C++ used to give special chara.pdf
Static Keyword Static is a keyword in C++ used to give special chara.pdf
KUNALHARCHANDANI1
 
Memory Management In C++
Memory Management In C++Memory Management In C++
Memory Management In C++
ShriKant Vashishtha
 
Csharp4 objects and_types
Csharp4 objects and_typesCsharp4 objects and_types
Csharp4 objects and_typesAbed Bukhari
 
Inheritance.ppt
Inheritance.pptInheritance.ppt
Inheritance.ppt
KevinNicolaNatanael
 

Similar to Online CPP Homework Help (20)

C++ Object oriented concepts & programming
C++ Object oriented concepts & programmingC++ Object oriented concepts & programming
C++ Object oriented concepts & programming
 
While writing program in any language, you need to use various variables to s...
While writing program in any language, you need to use various variables to s...While writing program in any language, you need to use various variables to s...
While writing program in any language, you need to use various variables to s...
 
11-Classes.ppt
11-Classes.ppt11-Classes.ppt
11-Classes.ppt
 
Object oriented design
Object oriented designObject oriented design
Object oriented design
 
Intake 37 4
Intake 37 4Intake 37 4
Intake 37 4
 
Intake 38 3
Intake 38 3Intake 38 3
Intake 38 3
 
Java căn bản - Chapter7
Java căn bản - Chapter7Java căn bản - Chapter7
Java căn bản - Chapter7
 
Chapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part IIChapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part II
 
C++ beginner's guide ch08
C++ beginner's guide ch08C++ beginner's guide ch08
C++ beginner's guide ch08
 
Presentation 3rd
Presentation 3rdPresentation 3rd
Presentation 3rd
 
Lecture 4. mte 407
Lecture 4. mte 407Lecture 4. mte 407
Lecture 4. mte 407
 
Classes-and-Objects-in-C++.pdf
Classes-and-Objects-in-C++.pdfClasses-and-Objects-in-C++.pdf
Classes-and-Objects-in-C++.pdf
 
C# classes objects
C#  classes objectsC#  classes objects
C# classes objects
 
Unit vi(dsc++)
Unit vi(dsc++)Unit vi(dsc++)
Unit vi(dsc++)
 
Lecture 9
Lecture 9Lecture 9
Lecture 9
 
Introduction to Python - Part Three
Introduction to Python - Part ThreeIntroduction to Python - Part Three
Introduction to Python - Part Three
 
Static Keyword Static is a keyword in C++ used to give special chara.pdf
  Static Keyword Static is a keyword in C++ used to give special chara.pdf  Static Keyword Static is a keyword in C++ used to give special chara.pdf
Static Keyword Static is a keyword in C++ used to give special chara.pdf
 
Memory Management In C++
Memory Management In C++Memory Management In C++
Memory Management In C++
 
Csharp4 objects and_types
Csharp4 objects and_typesCsharp4 objects and_types
Csharp4 objects and_types
 
Inheritance.ppt
Inheritance.pptInheritance.ppt
Inheritance.ppt
 

More from C++ Homework Help

cpp promo ppt.pptx
cpp promo ppt.pptxcpp promo ppt.pptx
cpp promo ppt.pptx
C++ Homework Help
 
CPP Homework Help
CPP Homework HelpCPP Homework Help
CPP Homework Help
C++ Homework Help
 
CPP homework help
CPP homework helpCPP homework help
CPP homework help
C++ Homework Help
 
CPP Programming Homework Help
CPP Programming Homework HelpCPP Programming Homework Help
CPP Programming Homework Help
C++ Homework Help
 
C++ Programming Homework Help
C++ Programming Homework HelpC++ Programming Homework Help
C++ Programming Homework Help
C++ Homework Help
 
C++ Homework Help
C++ Homework HelpC++ Homework Help
C++ Homework Help
C++ Homework Help
 
C++ Programming Homework Help
C++ Programming Homework HelpC++ Programming Homework Help
C++ Programming Homework Help
C++ Homework Help
 
Get Fast C++ Homework Help
Get Fast C++ Homework HelpGet Fast C++ Homework Help
Get Fast C++ Homework Help
C++ Homework Help
 
Best C++ Programming Homework Help
Best C++ Programming Homework HelpBest C++ Programming Homework Help
Best C++ Programming Homework Help
C++ Homework Help
 
CPP Homework Help
CPP Homework HelpCPP Homework Help
CPP Homework Help
C++ Homework Help
 
CPP Programming Homework Help
CPP Programming Homework HelpCPP Programming Homework Help
CPP Programming Homework Help
C++ Homework Help
 
CPP Homework Help
CPP Homework HelpCPP Homework Help
CPP Homework Help
C++ Homework Help
 
Online CPP Homework Help
Online CPP Homework HelpOnline CPP Homework Help
Online CPP Homework Help
C++ Homework Help
 
CPP Assignment Help
CPP Assignment HelpCPP Assignment Help
CPP Assignment Help
C++ Homework Help
 
CPP Homework help
CPP Homework helpCPP Homework help
CPP Homework help
C++ Homework Help
 
CPP homework help
CPP homework helpCPP homework help
CPP homework help
C++ Homework Help
 
CPP Homework Help
CPP Homework HelpCPP Homework Help
CPP Homework Help
C++ Homework Help
 
Cpp Homework Help
Cpp Homework Help Cpp Homework Help
Cpp Homework Help
C++ Homework Help
 

More from C++ Homework Help (18)

cpp promo ppt.pptx
cpp promo ppt.pptxcpp promo ppt.pptx
cpp promo ppt.pptx
 
CPP Homework Help
CPP Homework HelpCPP Homework Help
CPP Homework Help
 
CPP homework help
CPP homework helpCPP homework help
CPP homework help
 
CPP Programming Homework Help
CPP Programming Homework HelpCPP Programming Homework Help
CPP Programming Homework Help
 
C++ Programming Homework Help
C++ Programming Homework HelpC++ Programming Homework Help
C++ Programming Homework Help
 
C++ Homework Help
C++ Homework HelpC++ Homework Help
C++ Homework Help
 
C++ Programming Homework Help
C++ Programming Homework HelpC++ Programming Homework Help
C++ Programming Homework Help
 
Get Fast C++ Homework Help
Get Fast C++ Homework HelpGet Fast C++ Homework Help
Get Fast C++ Homework Help
 
Best C++ Programming Homework Help
Best C++ Programming Homework HelpBest C++ Programming Homework Help
Best C++ Programming Homework Help
 
CPP Homework Help
CPP Homework HelpCPP Homework Help
CPP Homework Help
 
CPP Programming Homework Help
CPP Programming Homework HelpCPP Programming Homework Help
CPP Programming Homework Help
 
CPP Homework Help
CPP Homework HelpCPP Homework Help
CPP Homework Help
 
Online CPP Homework Help
Online CPP Homework HelpOnline CPP Homework Help
Online CPP Homework Help
 
CPP Assignment Help
CPP Assignment HelpCPP Assignment Help
CPP Assignment Help
 
CPP Homework help
CPP Homework helpCPP Homework help
CPP Homework help
 
CPP homework help
CPP homework helpCPP homework help
CPP homework help
 
CPP Homework Help
CPP Homework HelpCPP Homework Help
CPP Homework Help
 
Cpp Homework Help
Cpp Homework Help Cpp Homework Help
Cpp Homework Help
 

Recently uploaded

GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
Nguyen Thanh Tu Collection
 
Additional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdfAdditional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdf
joachimlavalley1
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
Delapenabediema
 
Basic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumersBasic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumers
PedroFerreira53928
 
Introduction to Quality Improvement Essentials
Introduction to Quality Improvement EssentialsIntroduction to Quality Improvement Essentials
Introduction to Quality Improvement Essentials
Excellence Foundation for South Sudan
 
Cambridge International AS A Level Biology Coursebook - EBook (MaryFosbery J...
Cambridge International AS  A Level Biology Coursebook - EBook (MaryFosbery J...Cambridge International AS  A Level Biology Coursebook - EBook (MaryFosbery J...
Cambridge International AS A Level Biology Coursebook - EBook (MaryFosbery J...
AzmatAli747758
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
EugeneSaldivar
 
How to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS ModuleHow to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS Module
Celine George
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
Vivekanand Anglo Vedic Academy
 
Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
Tamralipta Mahavidyalaya
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
EverAndrsGuerraGuerr
 
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
BhavyaRajput3
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
TechSoup
 
How to Break the cycle of negative Thoughts
How to Break the cycle of negative ThoughtsHow to Break the cycle of negative Thoughts
How to Break the cycle of negative Thoughts
Col Mukteshwar Prasad
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Thiyagu K
 
The Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve ThomasonThe Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve Thomason
Steve Thomason
 
The Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdfThe Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdf
kaushalkr1407
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
DeeptiGupta154
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
siemaillard
 
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptxStudents, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
EduSkills OECD
 

Recently uploaded (20)

GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
 
Additional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdfAdditional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdf
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
 
Basic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumersBasic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumers
 
Introduction to Quality Improvement Essentials
Introduction to Quality Improvement EssentialsIntroduction to Quality Improvement Essentials
Introduction to Quality Improvement Essentials
 
Cambridge International AS A Level Biology Coursebook - EBook (MaryFosbery J...
Cambridge International AS  A Level Biology Coursebook - EBook (MaryFosbery J...Cambridge International AS  A Level Biology Coursebook - EBook (MaryFosbery J...
Cambridge International AS A Level Biology Coursebook - EBook (MaryFosbery J...
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
 
How to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS ModuleHow to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS Module
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
 
Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
 
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
 
How to Break the cycle of negative Thoughts
How to Break the cycle of negative ThoughtsHow to Break the cycle of negative Thoughts
How to Break the cycle of negative Thoughts
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
 
The Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve ThomasonThe Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve Thomason
 
The Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdfThe Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdf
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
 
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptxStudents, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
 

Online CPP Homework Help

  • 1. For any Homework related queries, Call us at : - +1 678 648 4277 You can mail us at :- info@cpphomeworkhelp.com or reach us at :- https://www.cpphomeworkhelp.com/
  • 2. 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(initialValue2) { … } cpphomeworkhelp.com
  • 3. 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 Rectangleclass 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 Timeclass 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 timefunction 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 Timeobject stores later on. cpphomeworkhelp.com
  • 4. Create a class called Complexfor 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. b. Rewrite the constructor to use the member initializer syntax instead of an assignment statement. Problem 2 cpphomeworkhelp.com
  • 5. 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(); cpphomeworkhelp.com
  • 6. … }; 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 getMartianCountas 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. cpphomeworkhelp.com
  • 7. 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: StockPurchase(const double newPrice) { // When someone buys a stock, modify the default price // according to how much they were willing to pay cpphomeworkhelp.com
  • 8. 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 cpphomeworkhelp.com
  • 9. 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. cpphomeworkhelp.com
  • 10. 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 cpphomeworkhelp.com
  • 11. 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 Creditfunction. 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 cpphomeworkhelp.com
  • 12. 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.) cpphomeworkhelp.com
  • 13. 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 Arrayobjects and manipulating them. cpphomeworkhelp.com
  • 14. Problem 1 (a) #include <ctime> class Time { time_t t; public: // or long, or int Time( long initialTime = time(0) ) { t = initialTime; } long getTime() { return t; }; void setTime(long newTime) { t = newTime; }; }; (b) #include <ctime> // or long, or int cpphomeworkhelp.com
  • 15. Time(time_t initialTime = time(0) ) : t(initialTime) {} int getTime() { return t; } void setTime(time_t newTime) { t= newTime; } }; Problem 2 #include <iostream> using namespace std; class Complex { double real, imaginary; public: Complex(double realPart=0, double imagPart=0) {real=realPart; imaginary=imagPart;}; double getReal() class Time { time_t t; public: cpphomeworkhelp.com
  • 16. { 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 ); }; Complex multiply(const Complex &obj) const { return Complex(real * obj.real - imaginary * obj.imaginary, real * obj.imaginary + imaginary * obj.real); cpphomeworkhelp.com
  • 17. }; }; 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. cpphomeworkhelp.com
  • 18. 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) { cpphomeworkhelp.com
  • 19. 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(double amountToDebit) { if(balance >= amountToDebit) { balance -= amountToDebit; return true; } else { cerr << "Debit amount exceeded account balance."<<endl; return false; } } cpphomeworkhelp.com
  • 20. 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); }; Account::Account(double initBalance):balance(initBalance) { if(balance<0.0) { cpphomeworkhelp.com
  • 21. 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 *internalArray; public: Array(int numElements); cpphomeworkhelp.com
  • 22. Array.cpp #include <iostream> #include <string> #include "Array.h" using namespace std; Array::Array(int numElements) : size(numElements) { internalArray = new int[size]; for(int i = 0; i < size; i++) internalArray[i] = 0; } Array::Array(int initialValues[], int numElements) : size(numElements) { 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(); }; cpphomeworkhelp.com
  • 23. { 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; }; 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(); }; cpphomeworkhelp.com