Here is my code:
#include <iostream>
#include <string>
using namespace std;
class Sport{
protected:
string name;
double hours;
virtual double returnCalories()=0;
public:
Sport():name("Not defined"),hours(0.0){}
Sport(string n, double c):name(n),hours(c){}
virtual ~Sport(){}
void setName(string x){
name=x;
}
void setTime(double x){
hours=x;
}
};
class Running:public Sport{
public:
static const int CALORIES = 950;
Running(){}
~Running(){}
double returnCalories(){
return hours*CALORIES;
}
};
class Activity{
public:
Sport* one;
Activity(){}
Activity(string n,double time){
one->setName(n);
one->setTime(time);
}
~Activity(){}
};
class Diary{
private:
Activity list_activity[10];
int counter_activity;
public:
Diary():counter_activity(0){}
~Diary(){}
void addActivity(Activity x){
// add activities
}
double sumCalories(){
for(int i=0;i<10;i++){
if(list_activity[i].one->getName()=="Running"){
// I want to call returnCalories() of class Running
}
}
}
};
int main() {
Activity test("Running",3.2);
Diary test2;
test2.addActivity(test);
return 0;
}
Now I have a question:
How is it possible to call returnCalories() of class Running where I want to ? ( it's commented in the code )
Is this even possible, or should I change my logic somehow ?
It's crashing because you have not initialized Sport *one; and you're attempting to call methods on a null pointer. You need to first create a Running object within the Activity constructor using the "new" operator like so:
one = new Running(n, time);
Create an overloaded constructor in your "Running" class that takes the appropriate arguments as well, so that you can initialize your variable as shown above.
Related
I wrote a simple c++ program and it gave me error in the setter, function definition does not declare parameters, although there was a setter above it and it worked correctly the error is in the function named setattack here is the code:
{
#include <iostream>
using namespace std;
class Warrior{
private:
string name;
int attack;
int defense;
public:
void setname(string m){
name=m;
}
string getname(){
return name;}
void setattack{int aw}{
attack=aw;
}
int getattack(){
return attack;}
void setdefense{int dw}{
defenset=dw;
}
int getdefense(){
return defense;}
void kill(const Monster &monster){
}
};
int main()
{
return 0;
}
}
In your set function you have used {} curly braces for arguments I think it should be (), and there is an extra } after main.
For my homework I have to do a class Game in C++ that has name, size, and a list of updates that contain date of update and some information about that update. (for example : 22.05.2018 Bug fixed at quest 3). Here is what i tried, but it doesn't work. Game.h:
class Game{
public:
struct update{
string date;
string info;
};
string name;
double size;
list<update>l;
Game(string name, double size, list<update>l);
virtual ~Game();
};
and in Game.cpp:
Game::Game(string name, double size, list<update>l){
this->name=name;
this->size=size;
this->l=l;
}
In int main I created a list:
int main()
{
list<update>mylist;
update u1,u2,u3;
u1.date="20.05.2018";
u1.info="Mission 3 bug fixed";
u2.date="25.05.2018";
u2.info="New quest";
mylist.push_back(u1);
mylist.push_back(u2);
Game g("Gta5",60.0,mylist);
return 0;
}
i get this error:
no matching function for call to 'Game::Game(const char [4], double, std::__cxx11::list<update>&)'|
Or if you want to keep the nested class update:
#include <string>
#include <list>
using std::string;
using std::list;
class Game{
public:
struct update{
string date;
string info;
};
string name;
double size;
list<update>l;
Game(string name, double size, list<update>l);
virtual ~Game() {}
};
Game::Game(string name, double size, list<update>l){
this->name=name;
this->size=size;
this->l=l;
}
int main()
{
list<Game::update> mylist; // use Game::update to access nested class
Game::update u1,u2,u3;
u1.date="20.05.2018";
u1.info="Mission 3 bug fixed";
u2.date="25.05.2018";
u2.info="New quest";
mylist.push_back(u1);
mylist.push_back(u2);
Game g("Gta5",60.0,mylist);
return 0;
}
Try this,
#include<bits/stdc++.h>
using namespace std;
struct update
{
string date;
string info;
update(string date,string info){
this->date=date;
this->info=info;
}
};
class Game{
public:
string name;
double size;
list<update>l;
Game(string name, double size, list<update>l);
// virtual ~Game();
};
Game::Game(string name, double size, list<update>l){
this->name=name;
this->size=size;
this->l=l;
}
int main(){
list<update> l,m;
l.push_front(update("10/10/2017","some bug fixed"));
double size=100;
string name="Game1";
Game obj(name,size,l);
cout<<obj.name<<" "<<obj.size<<" "<<endl;
m=obj.l;
list<update>::iterator i;
for(i=m.begin();i!=m.end();i++){
update structObj=*i;
cout<<structObj.date<<" "<<structObj.info<<endl;
}
return 0;
}
Output
Game1 100
10/10/2017 some bug fixed
Based on my Snack.cpp, Snack header file, MiniVend header file & miniVend.cpp file, I am trying to move my Snack private member - price into my MiniVend.cpp file to generate the amount * price to return a total value of items in my machine. How do I access the price from another class?
Portion of my miniVend.cpp file
double miniVend::valueOfSnacks()
{
return //// I don't know how to get snacks price in here? I need to access snacks & getSnackPrice.
}
miniVend header
#ifndef MINIVEND
#define MINIVEND
#include <string>
#include "VendSlot.h"
#include "Snack.h"
using std::string;
class miniVend
{
public:
miniVend(VendSlot, VendSlot, VendSlot, VendSlot, double); //constructor
int numEmptySlots();
double valueOfSnacks();
//void buySnack(int);
double getMoney();
~miniVend(); //desructor
private:
VendSlot vendslot1; //declare all the vending slots.
VendSlot vendslot2; //declare all the vending slots.
VendSlot vendslot3; //declare all the vending slots.
VendSlot vendslot4; //declare all the vending slots.
double moneyInMachine; //money in the machine
};
#endif // !MINIVEND
Snack.cpp
#include "Snack.h"
#include <iostream>
#include <string>
using std::endl;
using std::string;
using std::cout;
using std::cin;
Snack::Snack() //default constructor
{
nameOfSnack = "bottled water";
snackPrice = 1.75;
numOfCalories = 0;
}
Snack::Snack(string name, double price, int cals)
{
nameOfSnack = name;
snackPrice = price;
numOfCalories = cals;
}
Snack::~Snack()
{
}
string Snack::getNameOfSnack()
{
return nameOfSnack;
}
double Snack::getSnackPrice()
{
return snackPrice;
}
int Snack::getNumOfCalories()
{
return numOfCalories;
}
Snack.h file
#ifndef SNACK_CPP
#define SNACK_CPP
#include <string>
using std::string;
class Snack
{
private:
string nameOfSnack;
double snackPrice;
int numOfCalories;
public:
Snack(); //default constructor
Snack(string name, double price, int cals); //overload constructor
~Snack(); //destructor
//Accessor functions
string getNameOfSnack(); //returns name of snack
double getSnackPrice(); //returns the price of the snack
int getNumOfCalories(); //returns number of calories of snack
};
#endif // !SNACK_CPP
Assuming getSnackPrice() is public, and Snack.h does exist, you should just be able to call
snackObject.getSnackPrice() * ammount
what you need is friend keyword. Define the
friend class className;
I don't really understand why you don't just implement get()? Accessing private data is really bad. You are breaking the encapsulation. But if you really want to know (i.e. you should NOT do it, it is really BAD), then you just return a reference to a private data as shown below
#include <iostream>
class A
{
public:
A(int a) : x(a) {}
int &getPrivateDataBAD() { return x; }
void print() { std::cout << x << std::endl; }
private:
int x;
};
class B
{
public:
void print(int &s) { std::cout << s << std::endl; }
};
int main()
{
A obj(2);
B bObj;
bObj.print( obj.getPrivateDataBAD() );
return 0;
}
I'm having a bit of trouble with classes used within classes, from header files.
I have a class time in time.h:
#ifndef TIME_H
#define TIME_H
#include <iostream>
using namespace std;
class Time
{
private:
int hour, minute, second;
public:
Time();
~Time();
Time(int h, int m, int s);
int getHour();
int getMinute();
int getSecond();
void setHour(int hour);
void setMinute(int minute);
void setSecond(int second);
Time getTimeFromUser(Time b);
bool validTime(Time a);
void print24Hour(Time a);
void print12Hour(Time b);
};
#endif
Schedule.h
#ifndef SCHEDULE_H
#define SCHEDULE_H
#include <iostream>
#include "time.h"
using namespace std;
class Class
{
private:
string name;
int credits;
bool majorRequirement;
double avgGrade;
string days;
Time startTime;
Time endTime;
public:
Class();
~Class();
Class(string namae, int cred, bool majorReq, double avg, string day);
//Mutate
void setName(string h);
void setCredits(int c);
void setMajorRequirement(bool set);
void setAvgGrade(double g);
void setDays(string d);
void getStartTimeFromUser(Time b);
void getEndTimeFromUser(Time e);
// Access
string getName();
int getCredits();
bool getMajorRequirement();
double getAvgGrade();
string getDays();
Time& getStartTime();
Time& getEndTime();
};
#endif
Schedule.cpp:
Class::Class()
{
string name = "";
int credits = 0;
bool majorRequirement = false;
double avgGrade = 0.0;
string days = "";
}
Time::Time()
{
int hour = 0;
int minute = 0;
int second = 0;
}
Class::Class(string namae, int cred, bool majorReq, double avg, string day)
{
name = namae;
credits = cred;
majorRequirement = majorReq;
avgGrade = avg;
days = day;
}
Time::Time(int h, int m, int s)
{
second = s;
minute = m;
hour = h;
}
Time getTimeFromUser(Time b)
{
string time = "";
string hourS, minuteS, secondS = new string();
getline(cin,time);
hourS = time.substr(0,2);
minuteS = time.substr(3,2);
secondS = time.substr(6,2);
b.hour = atoi(hourS.c_str());
b.minute = atoi(minuteS.c_str());
b.second = atoi(secondS.c_str());
return b;
}
void getStartTimeFromUser(Time b)
{
startTime = getTimeFromUser(b);
}
void getEndTimeFromUser(Time e)
{
endTime = getTimeFromUser(e);
}
Other Mutators and Accessors here.
Main is long. Here is the severely condensed version:
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <iomanip>
#include "time.h"
#include "schedule.h"
using namespace std;
int main()
{
// Expecting that variables are properly declared
Class * klass = new Class[classcount];
cout << "Enter the start time for the class (format is HH:MM:SS): ";
klass[i].getStartTimeFromUser(classB);
cout << "Enter the end time for the class (format is HH:MM:SS): ";
klass[i].getEndTimeFromUser(classE);
for(int i = 0; i < classcount; i++)
{
// Data collected via getline and changed through mutators/accessors
// Problems arise when working with Time
klass[i].getStartTime().print24hour();
}
}
I get quite a few "hour, second, minute, etc." are private errors, I'm guessing I'm doing something simple in a rather wrong way. Please help.
I get a lot of this:
time.h:10:7: error: ‘int Time::hour’ is private
schedule.cpp:146:4: error: within this context
time.h:10:13: error: ‘int Time::minute’ is private
schedule.cpp:147:4: error: within this context
time.h:10:21: error: ‘int Time::second’ is private
schedule.cpp:148:4: error: within this context
schedule.cpp: In function ‘void getStartTimeFromUser(Time)’:
schedule.cpp:155:16: error: ‘setStartTime’ was not declared in this scope
schedule.cpp: In function ‘void getEndTimeFromUser(Time)’:
schedule.cpp:160:2: error: ‘endTime’ was not declared in this scope
time.h: In function ‘bool validTime(Time)’:
There are several errors in your code:
I assume class in your main() function represents an array of
Class; but this is illegal, since class is a C++ keyword.
You are trying to access a private member of a Class object
(class[i].startTime). This is illegal again. You would need a
public accessor to that data member:
You are calling a function that does not exist (print24()). If you
intended to call print24hour(), this function takes no parameters.
Putting it all together, you need to do three things:
Add an accessor for startTime in Class:
class Class
{
//...
public:
Time GetStartTime() {return startTime;}
};
Use a legal name for your array and use std::vector or std::array:
std::vector<Class> classArray;
// OR:
std::array<Class, SIZE> classArray;
Call the right methods correctly:
classArray[i].GetStartTime().print24hour();
I you want to access class[i].startTime.print24(getStartTime()) from main you need to make startTimepublic.
If this is good style is a different question.
You are trying to access the private members of a class using the object directly.
Please read about public and private access specifiers here.
class Class
{
private:
Time startTime;
public:
const Time & getStartTime(){
return startTime;
}
};
int main()
{
Class c;
c.getStartTime().print24Hour();
}
You want either that, or make startTime public.
Note the const; if you don't want the returned reference to be const, then make startTime public right now. You may think that making it private improves encapsulation; and yes, it does, as long as you don't provide read-write access to the variable, which happens if you don't mark the member function return type const.
If your printing function isn't marked const, then your const-correctness doesn't exist. If using const reference as return type here, then you have some things to fix.
Related reading: Pseudo-Classes and Quasi-Classes.
I have a multilevel inheritance (from Ship class -> MedicShip class -> Medic class) with virtual function code as below. I suppose the result should be :
Medic 10
Medic 10
But it generated strange result. On the other hand, if I only use one level inheritance (from Ship class -> Medic class without MedicShip class in between) the result will be OK. Could you find my mistake please? Many thank....
#ifndef FLEET_H
#define FLEET_H
#include <string>
#include <vector>
using namespace std;
class Ship
{
public:
Ship(){};
~Ship(){};
int weight;
string typeName;
int getWeight() const;
virtual string getTypeName() const = 0;
};
class MedicShip: public Ship
{
public:
MedicShip(){};
~MedicShip(){};
string getTypeName() const;
};
class Medic: public MedicShip
{
public:
Medic();
};
class Fleet
{
public:
Fleet(){};
vector<Ship*> ships;
vector<Ship*> shipList() const;
};
#endif // FLEET_H
#include "Fleet.h"
#include <iostream>
using namespace std;
vector<Ship*> Fleet::shipList() const
{
return ships;
}
int Ship::getWeight() const
{
return weight;
}
string Ship::getTypeName() const
{
return typeName;
}
string MedicShip::getTypeName() const
{
return typeName;
}
Medic::Medic()
{
weight = 10;
typeName = "Medic";
}
int main()
{
Fleet fleet;
MedicShip newMedic;
fleet.ships.push_back(&newMedic);
fleet.ships.push_back(&newMedic);
for (int j=0; j< fleet.shipList().size(); ++j)
{
Ship* s = fleet.shipList().at(j);
cout << s->getTypeName() << "\t" << s->getWeight() << endl;
}
cin.get();
return 0;
}
You haven't created any instances of class Medic. Did you mean to say
Medic newMedic;
instead of
MedicShip newMedic;
perhaps? So, the Medic constructor isn't being called and weight and typeName aren't being initialized.
~Ship(){};
The first mistake is right here. This destructor should be virtual if you want to delete derived class objects through base class pointer.