How can I create a default constructor c++? [closed] - c++

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 22 days ago.
Improve this question
I'm currently learning how to code object oriented and I've created 2 classes (Applicant and OfferLetter) and trying to inherit those 2 classes into a third class (Software Engineer). I've gotten it structured for the most part however im getting an error code on my compiler that says "No default constructor exists for the class "OfferLetter". What can i do to fix this error?
#include <iostream>
using namespace std;
class Applicant{
private:
string Name;
string JobTitle;
string Degree;
int YearsOfExpiremce;
int Age;
public:
//Name
void setName(string name){
Name = name;
}
string getName(){
return Name;
}
//JobTitle
void setJobTitle(string jobtitle){
JobTitle = jobtitle;
}
string getJobTitle(){
return JobTitle;
}
//Degree
void setDegree(string degree){
Degree = degree;
}
string getDegree(){
return Degree;
}
//Expirence
void setExpirence(int expirence){
YearsOfExpiremce = expirence;
}
int getExpirence(){
return YearsOfExpiremce;
}
//Age
void setAge(int age){
Age = age;
}
int getAge(){
return Age;
}
//Constructor
Applicant(string name, string jobtitle, string degree, int expirence, int age){
Name = name;
JobTitle = jobtitle;
Degree = degree;
YearsOfExpiremce = expirence;
Age = age;
}
};
class OfferLetter{
private:
int BaseSalary;
int SignOnBonus;
int Stocks;
int Incentives;
public:
//Base Salary
void setSalary(int salary){
BaseSalary = salary;
}
int getSalary(){
return BaseSalary;
}
//Sign-On Bonus
void setBonus(int bonus){
SignOnBonus = bonus;
}
int getBonus(){
return SignOnBonus;
}
//Stocks
void setStocks(int stocks){
Stocks = stocks;
}
int getStocks(){
return Stocks;
}
//Incentives
void setIncentives(int incentives){
Incentives = incentives;
}
int getIncentives(){
return Incentives;
}
//Constructor
OfferLetter(int salary, int bonus, int stocks, int incentives){
BaseSalary = salary;
SignOnBonus = bonus;
Stocks = stocks;
Incentives = incentives;
}
};
class SoftwareEngineer: public Applicant, public OfferLetter{
public:
string ProgrammingLanguage;
string JobDescription;
SoftwareEngineer(string name, string jobtitle, string degree, int expirence, int age, int salary, int bonus,
int stocks, int incentives, string language, string jd)
:Applicant(name, jobtitle, degree, expirence, age)
:OfferLetter(salary, bonus, stocks, incentives)
{
ProgrammingLanguage = language;
JobDescription = jd;
}
void DisplaySEOfferLetter(){
cout << "Congratulations on your job offer, Here is your total compensation. " << endl;
cout << "Please respond to us in the next 5 days to confirm your Job Offer." << endl;
cout << endl;
cout << "Total Compensation " << endl;
cout << "-------------------" << endl;
cout << "Role: Software Engineer " << endl;
cout << "Job Description: $" << endl;
cout << "Base Salary : $" << endl;
cout << "Sign-On Bonus: $" << endl;
cout << "Stocks : $" << endl;
cout << "Incentives : $" << endl;
cout << endl;
}
};

I think the problem is not the default constructor missing, but that you have a syntax error in your code:
SoftwareEngineer(string name, string jobtitle, string degree,
int expirence, int age, int salary, int bonus,
int stocks, int incentives, string language, string jd)
:Applicant(name, jobtitle, degree, expirence, age)
:OfferLetter(salary, bonus, stocks, incentives)
{
}
You attempt to create two constructor initializer lists, which is wrong. A constructor have a single comma-separated list:
SoftwareEngineer(string name, string jobtitle, string degree,
int expirence, int age, int salary, int bonus,
int stocks, int incentives, string language, string jd)
: Applicant(name, jobtitle, degree, expirence, age), // Note comma here
OfferLetter(salary, bonus, stocks, incentives) // No colon on this line
{
}
Note that you can initialize member variables using the initializer list as well, and it's recommended to use that instead of assignment inside the constructor body:
SoftwareEngineer(string name, string jobtitle, string degree,
int expirence, int age, int salary, int bonus,
int stocks, int incentives, string language, string jd)
: Applicant(name, jobtitle, degree, expirence, age), // Note comma here
OfferLetter(salary, bonus, stocks, incentives), // No colon on this line
ProgrammingLanguage(language), // Added initialization
JobDescription(jd) // of member variables
{
// Now this can be totally empty
}

Related

How to read the value and output the value in C++

first of all am very new to C++. I am having some problem with my code. The program should able to get/read the value user entered and output it back. I tried get/set C++ methods, but am having some problem with getting and outputting the value in my main. The following is my code,
#include <iostream>
using namespace std;
class Store {
public:
//get and Set Price
void setPrice(int x){
price = x;
}
int getPrice(){
return price;
}
//Get and set % Marked Up
void setPercentageMarkedUp(int y){
markedUpPrice = y;
}
int getPercentageMarkedUp(){
return markedUpPrice;
}
//Get and set percentage Sales tax
void setPercentageSalesTax(int y){
percSalesTax = y;
}
int getPercentageSalesTax(){
return percSalesTax;
}
private:
int price;
int markedUpPrice;
int percSalesTax;
};
int main(){
int price;
Store obj;
cout << "enter the Original Price of the item: "<<endl;
obj.getPrice();
cout<<"the value is:"<<price<<endl;
return 0;
}
As am very new to both C++ and StackOverflow, please dont downgrade me for asking this simple question. I know its very basic. Will definitely appreciate those who helps. Thanks in advance.
Just need to update the main as follows
int main(){
Store obj;
int n_price;
cout << " Enter Original Price: " << endl;
cin >> n_price;
obj.setPrice(n_price);
cout << "Original Price: " << n_price<< endl;
return 0;
}
Thanks everyone. :)

C++ object oriented problems [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
This is an assignment i am trying to figure out:
Create a new project named Project3 and create a class named Rover
Within the Rover class, specify the following member instance variables:
name(string)
x position on a grid (integer)
y position on a grid (integer)
direction by compass – N, S, E, or W (String)
speed (0 – 5 meters per second, integer)
Within the Rover class, specify the following methods:
Default constructor – set the rover’s position to (0,0), its speed to 0, its direction to
North.
Constructor that receives parameters to initialize all five instance variables described above
Setter methods for each instance variable
Getter methods for each instance variable
getRoverData – returns a string that displays values for each instance variable of the
current rover object, placing each value on a separate line, as follows:
Rover name: A
X-position: 0
Y-position: 0
Direction: E
Speed: 1
Create a class client (main) that creates an array of the a maximum of five rovers and gets the initial
values for all rovers from the user. After the user specifies values for each rover, display a summary
of the rover’s values as shown above.
I have about a billion errors and i dont know why.
using namespace std;
class Rover {
private:
string name;
int x;
int y;
string direction;
int speed;
int position[10][10];
public:
void Rover();
void constructor(string name, int x, int y, string direction, int speed);
void setName(string name);
void setX(int x);
void setY(int y);
void setDirection(string direction);
void setSpeed();
string getName();
int getX();
int getY();
string getDirection();
int getSpeed();
string getRoverData();
};
void Rover::Rover() {
r1.position[0][0];
r1.speed = 0;
r1.direction = "N";
}
string Rover::getRoverData() {
cout << "Rover name: " << r1.getName() << endl;
cout << "X-position: " << r1.getX() << endl;
cout << "Y-position: " << r1.getY() << endl;
cout << "Direction: " << r1.getDirection() << endl;
cout << "Speed: " << r1.getSpeed() << endl;
}
void Rover::constructor(string name1, int x1, int y1, string direction1, int speed1) {
r1.name = name1;
r1.x = x1;
r1.y = y1;
r1.direction = direction1;
r1.speed = speed1;
}
void Rover::setName(string name) {
r1.name = name;
}
void Rover::setX(int x) {
r1.x = x;
}
void Rover::setY(int y) {
r1.y = y;
}
void Rover::setDirection(string direction) {
r1.direction = direction;
}
void Rover::setSpeed(int speed) {
r1.speed = speed;
}
string Rover::getName() {
return name;
}
int Rover::getX() {
return x;
}
int Rover::getY() {
return y;
}
string Rover::getDirection() {
return direction;
}
int Rover::getSpeed() {
return speed;
}
int main(int argc, char** argv) {
string name;
int x;
int y;
string direction;
int speed;
Rover r1;
r1.constructor("Yoda", 3, 3, "N", 3);
cout << "Enter name for Rover: ";
cin >> name;
r1.setName(name);
cout << "Enter its x position: ";
cin >> x;
r1.setX(x);
cout << "Enter its y position: ";
cin >> y;
r1.setY(y);
cout << "Enter direction N,E,S,W: ";
cin >> direction;
r1.setDirection(direction);
cout << "Enter its speed: ";
cin >> speed;
r1.setSpeed(speed);
r1.getRoverData();
return 0;
}
Your example appears incomplete. I'm guessing you just missed including the following lines in your post
#include <string>
#include <iostream>
using namespace std;
First, constructors do not have a return type so void Rover(); makes no sense. Remove void and you're golden there.
Second, what exactly do you think r1 is supposed to be? The compiler should tell you the identifier is undefined because it isn't. remove r1. from your member functions (i.e. anything function starting with Rover::. and you're golden there.
Third, what do you think r1.position[0][0] is going to do? It's just an expression that does nothing. Even position[0][0] is not going to do anything. Perhaps you want to initialize the array somehow but you haven't provided enough information to determine what you're trying to accomplish with it.
Fourth, the member function void Rover::setSpeed(int) has not been declared within the Rover class. Did you forget something? Based on your code it should be
int Rover::getSpeed()
{
return speed;
}
Fifth, void Rover::setSpeed(); doesn't make much sense unless it actually accepts an argument.

Error C2084 Function already has a body [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I've seen this all over the site and still nothing has been able to fix my problem. this is the only error I have and I have no idea how to fix this. I've tried commenting out different sections of the code just to see what happens and still nothing but errors. What is going on?
Her is the build error as well
error C2084: function 'HeroProfile::HeroProfile(void)' already has a body
Main.cpp
#include <iostream>
#include <string>
#include "HeroProfile.h"
using namespace std;
int main()
{
string name;
int race;
double weight;
cout << "Enter your Hero's name:";
cin>> name;
cout << "Enter your Hero's Race (1:Elf 2:Human 3 Dwarf)";
cin >> race;
cout << "Enters your Hero's weight ( in pounds):";
cin >> weight;
HeroProfile Hero_1(name, race, weight);
cout << endl << "hero's Name: " << Hero_1.getName() << endl <<
"Race: " << Hero_1.getRace() << endl <<
"Weight:" << Hero_1.getWeight() << endl;
cout << endl;
cout << "Enter your Hero's Name:";
cin >> name;
cout << "Enter your Race (1:Elf 2:Human 3 Dwarf)";
cin >> race;
cout <<"Enter your Hero's weight (in pounds)";
cin >> weight;
HeroProfile Hero_2(name, race, weight);
Hero_2.setName(name);
Hero_2.setRace(race);
Hero_2.setWeight(weight);
cout << endl << "Hero's Name: " << Hero_2.getName() << endl <<
"Race: " << Hero_2.getRace() << endl << "Weight: " << Hero_2.getWeight() << endl;
return 0;
}
The header File
#include <iostream>
#include <string>
using namespace std;
#ifndef HeroProfiel_H
#define HeroProfile_H
class HeroProfile
{
public:
//default constructor
HeroProfile();
//overlaod constructor
HeroProfile(string, int, double);
//destructor
~HeroProfile();
//Accesor functions
string getName() const;
// get name - returns name of patient
int getRace() const;
// getHeight-returns height of patient
double getWeight() const;
// getWeight- returns weight of patient
//Mutator Functions
void setName(string);
//set name of patient
//#param string - name of patient
void setRace(int);
//setHeight-sets heigh tof patient
//#param int- height iof patient
void setWeight(double);
//setWeight-sets weight of patiend
//#param double-weight of patient
private:
//Memeber variables
string newName;
int newRace;
double newWeight;
};
#endif
and the second .cpp file
#include "HeroProfile.h"
eroProfile::HeroProfile() //Default constructor
{
newRace = 0;
newWeight = 0.0;
}
HeroProfile::HeroProfile(string name, int race, double weight) //Overloaded Constructor
{
newName = name;
newRace = race;
newWeight = weight;
}
HeroProfile::HeroProfile()
}
}
//Accessors
string HeroProfile::getName() const
{
return newName;
}
int HeroProfile::getRace() const
{
return newRace;
}
double HeroProfile::getWeight() const
{
return newWeight;
}
//Mutators
void HeroProfile::setName(string name)
{
newName = name;
}
void HeroProfile::setRace(int race)
{
newRace = race;
}
void HeroProfile::setWeight(double weight)
{
newWeight = weight;
}
As others have noted, you have 2 definitions in your second cpp file for the HeroProfile default constructor HeroProfile::HeroProfile():
The first is
HeroProfile::HeroProfile() //Default constructor
{
newRace = 0;
newWeight = 0.0;
}
and the second is
HeroProfile::HeroProfile()
}
}
Based on the fact I don't see one, you probably intended for the second one to be your class destructor (as declared in your header file but not defined in your cpp file), in which case you should replace it with this:
HeroProfile::~HeroProfile()
}
}
I hope you didn't get confused by the fact that HeroProfile::HeroProfile(void) and HeroProfile::HeroProfile() are the same thing, so I thought I should point it out.
The message means exactly what it says. Ignoring typos, the first and third definitions in your second .cpp are for the same function.

How can I have both a parameterized and a default constructor in the same class?

I am attempting to write a class called student that has both a paramaterized and a default constructor in it, and the paramaterized version works fine, but the console crashes whenever I attempt to run the default constructor after assigning values manually.
Student.cpp:
Student::Student()
{
this -> firstName = firstName;
this -> lastName = lastName;
this -> maxGrades = maxGrades;
grades[maxGrades];
}
Student::Student(string fName, string lName, int mGrades)
{
firstName = fName;
lastName = lName;
maxGrades = mGrades;
grades[maxGrades];
}
Student::~Student()
{
}
void Student::setFirstName(string fName)
{
firstName = fName;
}
void Student::setLastName(string lName)
{
lastName = lName;
}
void Student::setMaxGrades(int mGrades)
{
mGrades = maxGrades;
grades[maxGrades];
}
string Student::getFirstName()
{
return firstName;
}
string Student::getLastName()
{
return lastName;
}
void Student::addGrade(int currentGradeNumber, double addedGrade)
{
if(currentGradeNumber < maxGrades)
{
grades[currentGradeNumber] = addedGrade;
cout << "grade " << currentGradeNumber << "is " << grades[currentGradeNumber] << endl;
}
}
double Student::calcAvg()
{
double sum = 0;
double avg = 0;
for(int i=0; i < maxGrades;i++)
{
sum += grades[i];
}
avg = sum/maxGrades;
return avg;
}
studentTest.cpp:
int main()
{
Student student1("Bill", "Nye", 3);
cout << "First Name: " << student1.getFirstName() << endl;
cout << "LastName: " << student1.getLastName() << endl;
student1.addGrade(0, 90);
student1.addGrade(1, 95);
student1.addGrade(2, 80);
cout << "Average is " << student1.calcAvg() << endl;
Student student2;
student2.setMaxGrades(2);
student2.setFirstName("Frank");
student2.setLastName("West");
cout << "\nFirst Name: " << student2.getFirstName() << endl;
cout << "Last Name: " << student2.getLastName() << endl;
student2.addGrade(0,50);
student2.addGrade(1,100);
cout << "Average is: " << student2.calcAvg();
return 0;
}
student.h:
class Student
{
private:
string firstName;
string lastName;
int maxGrades;
int numGrades;
double grades[];
public:
Student();
Student(string, string, int);
~Student();
void setFirstName(string);
void setLastName(string);
string getFirstName();
string getLastName();
void addGrade(int, double);
double calcAvg();
void setMaxGrades(int);
};
The student1 object runs fine, but the error comes when I try to use addGrade() or calcAvg() for student2. Any help would be appreciated.
Both your constructors are incorrect when they do this:
grades[maxGrades]; // This does not do what you think it does
This line does not crash in the parameterized constructor because maxGrades has a known value. Your default constructor, however, reuses an uninitialized value of maxGrades, causing undefined behavior.
You should rewrite your constructors using initializer lists. Assuming that grades is a std::vector<int>, you can do it like this:
Student::Student() : maxGrades(0)
{
// The remaining members will be initialized, because they have constructors.
}
Student::Student(string fName, string lName, int mGrades)
: firstName(fName)
, lastName(lName)
, maxGrades(mGrades)
, grades(mGrades, 0)
{
}
This does nothing useful:
this -> firstName = firstName;
this -> lastName = lastName;
this -> maxGrades = maxGrades;
Because you're in a method of your class, both this->firstName and firstName refer to the same variable—the same member variables. Likewise for the other two statements.
Without seeing how those members are declared, it's hard to say if this is the reason for your crash. But, it's definitely bogus code.
Also, this line does nothing useful as well:
grades[maxGrades];
And depending on how maxGrades and grades are declared, it is quite likely the source of your crash.
Edit: Your declaration for grades doesn't look good at all, because it's not allocating any storage for grades. You should consider using a std::vector<double> here, or at least specify a maximum size larger than the largest data set you'll be asked to work with. (eg. double grades[100];) But seriously, consider std::vector<double> here.
In your default constructor, you should assign reasonable default values to each of the members in an initializer list. Something like this:
Student::Student() :
firstName(""),
lastName(""),
maxGrades(0),
numGrades(0)
{
}
The constructor is called and whatever within in it is initialized as soon as the object is created. You are assigning values to first, maxgrade etc. only after creation of object. I don't think this is right.
Since grades is just a pointer, you are not allocating memory to it with the constructor lines "grades[maxGrades];". You have to do something like grades = new double[maxGrades], and only on a defined maxGrades (not defined in your default constructor). You could be doing a divide by zero in your average (if maxGrades = 0), and accessing an uninitialized pointer, grades. You need a way to set a default value to maxGrades, and then you need to do the "new" allocation of memory for grades.
Your function
void Student::setMaxGrades(int mGrades)
{
mGrades = maxGrades;
grades[maxGrades];
}
should read
maxGrades = mGrades;
grades = new double[maxGrades];

Printing Structure inputs from class member function

I would like to know how to input/initialize a start_date and end_date (which comes from a structure Date that has integers of month day and year from the function `initializeDate. Once I am able to initialize I assume I will be able to use the same logic in the printout member function.
struct Date
{
int month;
int day;
int year;
};
void initializeDate(Date &d)
{
cout<<"Please enter the month"<<endl;
cin>>start.month;
cout<<"Please enter the day"<<endl;
cin>>start.day;
cout<<"Please enter the year"<<endl;
cin>>start.year;
string dummy;
getline(cin, dummy);
}
edit: the error that I am getting is 'start' was not declared in this scope.
This is very basic, please read a good book on C++. Posting below because you have put in an effort :)
void Information::initializeDate(Date &d) //comes from the Information class.
{
// Commented as part of question change!
// Date d; // Guessing that the structure is the private member of the class.
cout<<"Please enter the month"<<endl;
cin>>d.month;
cout<<"Please enter the day"<<endl;
cin>>d.day;
cout<<"Please enter the year"<<endl;
cin>>d.year;
string dummy;
getline(cin, dummy);
}
** Just Edited the code as per your change in question
It looks like you keep updating the example code. Based on the current revision, I think this is what you want:
#include <iostream>
using namespace std;
struct Date
{
int month;
int day;
int year;
};
void initializeDate(Date &date)
{
cout<<"Please enter the month"<<endl;
cin>>date.month;
cout<<"Please enter the day"<<endl;
cin>>date.day;
cout<<"Please enter the year"<<endl;
cin>>date.year;
}
int main()
{
Date start, end;
initializeDate(start);
initializeDate(end);
cout << start.year << "/" << start.month << "/" << start.day << endl;
cout << end.year << "/" << end.month << "/" << end.day << endl;
return 0;
};
Ok, there are a couple of problems here, that you should target. First, to fix your code, the error is very simple: there isn't anywhere in your code in which a variable named start was declared/defined. So, the compiler is asking you what start is. You are trying, I assume, to initialize the values of the members of d, that you passed in the function initializeDate, and all you have to do is just replace every occurence of the word start with d, and you'll get:
void initializeDate(Date &d)
{
cout<<"Please enter the month"<<endl;
cin>> d.month;
cout<<"Please enter the day"<<endl;
cin>> d.day;
cout<<"Please enter the year"<<endl;
cin>> d.year;
string dummy;
getline(cin, dummy);
}
Now, although this works, it's not the best way to initialize the date. Since Date is a struct, you can initialize its members using a constructor method. This is achieved by writing it like this:
struct Date{
int day, month, year;
Date(int, int, int);
};
Date:: Date(int day, int month, int year){
this->day = day;
this->month = month;
this->year = year;
}
int main(){
Date today(11, 3, 2013);
cout << "today, the date is " << today.day << "-" << today.month << "-" << today.year << endl;
return 0;
}