Question

LW: Class Constructors Objectives Write a default constructor for a class. Note that this const...

LW: Class Constructors

Objectives

  • Write a default constructor for a class. Note that this constructor is used to build the object anytime an argument is not provided when it is defined.

  • Write a parameterized constructor that takes arguments that are used to initialize the class’s member variables

Labwork

  1. Download the code associated with this lab:

    • ColorConstructor.zip

      1. Main.cpp

      2. Color.h

      3. Color.cpp

  2. Compile and run the code.

    • The first line of output of the program should display nonsensical integers for the values of the color object declared on line 5, for example:
      Color values after declaration : (1355559696,32767,1764024374)

    • The program will then prompt you to input the r, g, and b values of a color, which will be assigned to the corresponding members of the color object, provided that they are valid (within the range 0-255).

  3. Create a default constructor that initializes the r, g, and b members to 255. After you've done this, compile your code and run the program. The output should be similar to that presented below:
    Color values after declaration: (255,255,255)
    followed by the previously observed input prompt.

  4. Create a parameterized constructor (this will be a new, additional constructor; leave the constructor that you modified in the previous step as is) that:

    • takes integer arguments for r, g, and b;

    • initializes the Color object’s members R, G, and B to the passed parameters r, g, and b using the initializer list syntax;

    • in the body, checks whether R, G, and B are valid values; if not, you should throw an instance of Color_error{} (throw Color_error{}).

  5. Let's test the code that you've written in the previous step. Comment out the code falling between //Part 1 and //Part 2; Uncomment the code below Part 2.

  6. Compile and run your code.

  7. Test your constructor by providing valid and invalid R,G,B values as input.

Main.cpp

//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
// CLASS CONSTRUCTORS LAB //
// MAIN.CPP //
// //
// Date ...: 18/MAR/2017 //
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////

//////////////////////////////////////////////////////////////////////////////
// Includes //
//////////////////////////////////////////////////////////////////////////////
#include <iostream>
#include <string>
#include <limits>
#include "Color.h"
using namespace std;

//////////////////////////////////////////////////////////////////////////////
// main //
//////////////////////////////////////////////////////////////////////////////

int main(int argc, char *argv[])
{
string prompt = "Please enter the r, g, and b integer values of a color, \nwith each separated by a space (e.x., \"255 255 255\"): ";
// Part 1
Color color;
cout << "Color values after declaration : " << color.to_str() << endl;
char cont = 'y'; // continue is yes
while (tolower(cont) == 'y') {
cout << prompt;
   int r, g, b;
while (!(cin >> r >> g >> b)) {
if (cin.bad() || cin.eof()) {
return 1;
} else if (cin.fail()) {
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
cout << "Invalid input." << endl << endl << prompt;
}
try {
           color.set_R(r); color.set_G(g); color.set_B(b);
           cout << "Color : " << color.to_str() << endl << endl;
}
catch (Color_error& e) {
   cout << "Invalid input." << endl << endl;
}
cout << "Do another? (y or Y) ";
cin >> cont;
}
/*
// Part 2
char cont = 'y'; // continue is yes
while (tolower(cont) == 'y') {
cout << prompt;
   int r, g, b;
while (!(cin >> r >> g >> b)) {
if (cin.bad() || cin.eof()) {
return 1;
} else if (cin.fail()) {
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
cout << "Invalid input." << endl << endl << prompt;
}
try {
           Color color(r, g, b);
           cout << "Color : " << color.to_str() << endl << endl;
}
catch (Color_error& e) {
   cout << "Invalid input." << endl << endl;
}
cout << "Do another? (y or Y) ";
cin >> cont;
}
*/
cout << "Goodbye!" << endl;
return 0;
}
Color.h

//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
// CLASS CONSTRUCTORS LAB //
// COLOR.H //
// //
// Date ...: 18/MAR/2017 //
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
#ifndef COLOR_H
#define COLOR_H

//////////////////////////////////////////////////////////////////////////////
// Dependencies //
//////////////////////////////////////////////////////////////////////////////
#include <iostream>
#include <string>
#include <sstream>

//////////////////////////////////////////////////////////////////////////////
// Color Class Definition //
//////////////////////////////////////////////////////////////////////////////
class Color_error {};
class Color {
public:
std::string to_str();
bool is_valid_val(int);
void set_R(int);
void set_G(int);
void set_B(int);
private:
int R;
int G;
int B;
};
//////////////////////////////////////////////////////////////////////////////
#endif

Color.cpp

//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
// CLASS CONSTRUCTORS LAB //
// COLOR.CPP //
// //
// Date ...: 18/MAR/2017 //
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////

//////////////////////////////////////////////////////////////////////////////
// Includes //
//////////////////////////////////////////////////////////////////////////////
#include "Color.h"

//////////////////////////////////////////////////////////////////////////////
// Color Class Member Definitions //
//////////////////////////////////////////////////////////////////////////////
std::string Color::to_str()
{
std::stringstream ss;
ss << '(' << R << ',' << G << ',' << B << ')';
return ss.str();
}

void Color::set_R(int r)
{
if (!is_valid_val(r))
throw Color_error{};
R = r;
}
void Color::set_G(int g)
{
if (!is_valid_val(g))
throw Color_error{};
G = g;
}
void Color::set_B(int b)
{
if (!is_valid_val(b))
throw Color_error{};
B = b;
}
bool Color::is_valid_val(int v)
{
if (v < 0 || v > 255)
return false;
else
return true;
}

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Done. Updated the classes: Color.h and Color.cpp to add two constructors

Main.cp: Updated to test the functionality. Commented part 1 and uncommented part 2

////////////////////////////////////////////////Color.h/////////////////////////////////////////////////////////////

//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
// CLASS CONSTRUCTORS LAB //
// COLOR.H //
// //
// Date ...: 18/MAR/2017 //
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
#ifndef COLOR_H
#define COLOR_H

//////////////////////////////////////////////////////////////////////////////
// Dependencies //
//////////////////////////////////////////////////////////////////////////////
#include <iostream>
#include <string>
#include <sstream>

//////////////////////////////////////////////////////////////////////////////
// Color Class Definition //
//////////////////////////////////////////////////////////////////////////////
class Color_error {};
class Color {
public:
Color();
Color(int,int,int);
std::string to_str();
bool is_valid_val(int);
void set_R(int);
void set_G(int);
void set_B(int);
private:
int R;
int G;
int B;
};

#endif

/////////////////////////////////////////////////End Color.h/////////////////////////////////////////////////////////////////////////////////////

/////////////////////////////////////////////////////Color.cpp//////////////////////////////////////////////////////////////////////////////////


#include "Color.h"

//////////////////////////////////////////////////////////////////////////////
// Color Class Member Definitions //
//////////////////////////////////////////////////////////////////////////////

//Default constructor that initialises R,G,B to 255
Color::Color() {
R = 255;
G = 255;
B = 255;
}
//Parameterise constructor that initialises R,G,B to values passed by the user. if there is
// some invalid value color exception is thrown
Color::Color(int r, int g, int b) {
if (!is_valid_val(g) || !is_valid_val(r) || !is_valid_val(b))
throw Color_error {
};

R = r;
G = g;
B = b;
}

std::string Color::to_str() {
std::stringstream ss;
ss << '(' << R << ',' << G << ',' << B << ')';
return ss.str();
}

void Color::set_R(int r) {
if (!is_valid_val(r))
throw Color_error {
};
R = r;
}

void Color::set_G(int g) {
if (!is_valid_val(g))
throw Color_error {
};
G = g;
}

void Color::set_B(int b) {
if (!is_valid_val(b))
throw Color_error {
};
B = b;
}

bool Color::is_valid_val(int v) {
if (v < 0 || v > 255)
return false;
else
return true;
}
/////////////////////////////////////////////////////End Color.cpp///////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////main.cpp///////////////////////////////////////////////////////////////////////

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

//////////////////////////////////////////////////////////////////////////////
// main //
//////////////////////////////////////////////////////////////////////////////

int main(int argc, char *argv[]) {
string prompt = "Please enter the r, g, and b integer values of a color, \nwith each separated by a space (e.x., \"255 255 255\"): ";
/*
// Part 1
Color color ;
cout << "Color values after declaration : " << color.to_str() << endl;
char cont = 'y'; // continue is yes
while (tolower(cont) == 'y') {
cout << prompt;
int r, g, b;
while (!(cin >> r >> g >> b)) {
if (cin.bad() || cin.eof()) {
return 1;
} else if (cin.fail()) {
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
cout << "Invalid input." << endl << endl << prompt;
}
try {
color.set_R(r);
color.set_G(g);
color.set_B(b);
cout << "Color : " << color.to_str() << endl << endl;
} catch (Color_error& e) {
cout << "Invalid input." << endl << endl;
}
cout << "Do another? (y or Y) ";
cin >> cont;
}
*/
// Part 2
char cont = 'y'; // continue is yes
while (tolower(cont) == 'y') {
cout << prompt;
int r, g, b;
while (!(cin >> r >> g >> b)) {
if (cin.bad() || cin.eof()) {
return 1;
} else if (cin.fail()) {
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
cout << "Invalid input." << endl << endl << prompt;
}
try {
Color color(r, g, b);
cout << "Color : " << color.to_str() << endl << endl;
}
catch (Color_error& e) {
cout << "Invalid input." << endl << endl;
}
cout << "Do another? (y or Y) ";
cin >> cont;
}

cout << "Goodbye!" << endl;
return 0;
}

/////////////////////////////////////////////////////////End main.cpp////////////////////////////////////////////////////////

ColorApp - NetBeans IDE 8.0.2 File Edit View Navigate Source Refactor Run Debug Profile Teem Iools Window Help Seardh (Ctrl +

Add a comment
Know the answer?
Add Answer to:
LW: Class Constructors Objectives Write a default constructor for a class. Note that this const...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Finish the class Matrix.h: class Matrix { public: Matrix(); //default constructor ~Matrix(); //destructor Matrix(const Matrix &);...

    Finish the class Matrix.h: class Matrix { public: Matrix(); //default constructor ~Matrix(); //destructor Matrix(const Matrix &); //copy constror Matrix(int row, int col); Matrix operator+(const Matrix &)const; //overload operator“+” Matrix& operator=(const Matrix &); //overload operator“=” Matrix transpose()const; //matrix transposition void display()const; //display the data private: int row; //row int col; //column int** mat; //to save the matrix }; //main.cpp #include <iostream> #include"Matrix.h" using namespace std; int main() { int row, col; cout << "input the row and the col for Matrix...

  • Finish the class Matrix.h: class Matrix { public: Matrix(); //default constructor ~Matrix(); //destructor...

    Finish the class Matrix.h: class Matrix { public: Matrix(); //default constructor ~Matrix(); //destructor Matrix(const Matrix &); //copy constror Matrix(int row, int col); Matrix operator+(const Matrix &)const; //overload operator“+” Matrix& operator=(const Matrix &); //overload operator“=” Matrix transpose()const; //matrix transposition void display()const; //display the data private: int row; //row int col; //column int** mat; //to save the matrix }; //main.cpp #include <iostream> #include"Matrix.h" using namespace std; int main() { int row, col; cout << "input the row and the col for Matrix...

  • Design a class named Triangle that extends GeometricObject class. The class contains: Three double data fields...

    Design a class named Triangle that extends GeometricObject class. The class contains: Three double data fields named side1, side2, and side3 with default values 1.0 to denote three sides of the triangle. A no-arg constructor that creates a default triangle with color = "blue", filled = true. A constructor that creates a triangle with the specified side1, side2, side3 and color = "blue", filled = true. The accessor functions for all three data fields, named getSide1(), getSide2(), getSide3(). A function...

  • I need to get this two last parts of my project done by tonight. If you...

    I need to get this two last parts of my project done by tonight. If you see something wrong with the current code feel free to fix it. Thank you! Project 3 Description In this project, use project 1 and 2 as a starting point and complete the following tasks. Create a C++ project for a daycare. In this project, create a class called child which is defined as follows: private members: string First name string Last name integer Child...

  • #include<iostream> #include<string> #include<iomanip> using namespace std; /* ********* Class Car ************* ********************************* */ class Car {...

    #include<iostream> #include<string> #include<iomanip> using namespace std; /* ********* Class Car ************* ********************************* */ class Car { private: string reportingMark; int carNumber; string kind; bool loaded; string choice; string destination; public: Car() { reportingMark = ""; carNumber = 0; kind = "Others"; loaded = 0; destination = "NONE"; } ~Car() { } void setUpCar(string &reportingMark, int &carNumber, string &kind, bool &loaded, string &destination); }; void input(string &reportingMark, int &carNumber, string &kind, bool &loaded,string choice, string &destination); void output(string &reportingMark, int &carNumber,...

  • USE C++. Just want to confirm is this right~? Write a class named RetailItem that holds...

    USE C++. Just want to confirm is this right~? Write a class named RetailItem that holds data about an item in a retail store. The class should have the following member variables: description: A string that holds a brief description of the item. unitsOnHand: An int that holds thw number of units currently in inventory. price: A double that holds that item's retail price. Write the following functions: -appropriate mutator functions -appropriate accessor functions - a default constructor that sets:...

  • employee.h ---------- #include <stdio.h> #include <iostream> #include <fstream> class Employee { private: int employeeNum; std::string name;...

    employee.h ---------- #include <stdio.h> #include <iostream> #include <fstream> class Employee { private: int employeeNum; std::string name; std::string address; std::string phoneNum; double hrWage, hrWorked; public: Employee(int en, std::string n, std::string a, std::string pn, double hw, double hwo); std::string getName(); void setName(std::string n); int getENum(); std::string getAdd(); void setAdd(std::string a); std::string getPhone(); void setPhone(std::string p); double getWage(); void setWage(double w); double getHours(); void setHours(double h); double calcPay(double a, double b); static Employee read(std::ifstream& in); void write(std::ofstream& out); }; employee.cpp ---------- //employee.cpp #include...

  • The following C++ code include 3 files: Patient.h, Patient.cpp and Main.cpp. The program basically creates and stores patient records. The original code has everything in a single .cpp file. I tried t...

    The following C++ code include 3 files: Patient.h, Patient.cpp and Main.cpp. The program basically creates and stores patient records. The original code has everything in a single .cpp file. I tried to divide the code in 3 parts (Patient.h, Patient.cpp and Main.cpp), but it is giving me errors. Patient.h #ifndef PATIENT_H #define PATIENT_H #include <string> #include "Patient.cpp" using namespace std; class Patient{ private : string firstname; string lastname; string location; static int cnt; int id; public : Patient(string, string, string);...

  • Greetings, everybody I already started working in this program. I just need someone to help me...

    Greetings, everybody I already started working in this program. I just need someone to help me complete this part of the assignment (my program has 4 parts of code: main.cpp; Student.cpp; Student.h; StudentGrades.cpp; StudentGrades.h) Just Modify only the StudentGrades.h and StudentGrades.cpp files to correct all defect you will need to provide implementation for the copy constructor, assignment operator, and destructor for the StudentGrades class. Here are my files: (1) Main.cpp #include <iostream> #include <string> #include "StudentGrades.h" using namespace std; int...

  • //Vehicle.h #pragma once #include<iostream> #include"Warranty.h" #include<string> using namespace std; class Vehicle{ protected:    string make; int year;   ...

    //Vehicle.h #pragma once #include<iostream> #include"Warranty.h" #include<string> using namespace std; class Vehicle{ protected:    string make; int year;    double mpg;    Warranty warranty;    static int numOfVehicles; public:    Vehicle();    Vehicle(string s, int y, double m, Warranty warranty);    Vehicle(Vehicle& v);    ~Vehicle();    string getMake();    int getYear();    double getGasMileage();    void setMake(string s);    void setYear(int y);    void setYear(string y);    void setGasMileage(double m);    void setGasMileage(string m);    void displayVehicle();    static int getNumVehicles();    Warranty getWarranty();    void setWarranty(Warranty& ); }; //Vehicle.cpp #include "Vehicle.h" #include <string> Vehicle::Vehicle() {    make = "unknown";    year =...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT