Composition syntax in C++ - c++

I am in the middle of getting my feet wet with the use of composition & classes in C++. A code snippet I came across implements composition in the following manner:
#include<iostream>
using namespace std;
class Engine {
public:
int power;
};
class Car {
public:
Engine e;
string company;
string color;
void show_details() {
cout << "Compnay is: " << company << endl;
cout << "Color is: " << color << endl;
cout << "Engine horse power is: " << e.power << endl;
}
};
int main() {
Car c;
c.e.power = 500;
c.company = "hyundai";
c.color = "black";
c.show_details();
return 0;
}
This compiles fine, and runs. One thing I do not like about this implementation is the actual location of the function "void show_details", which I would prefer to place outside.
However, if I naively try to do the following:
#include<iostream>
using namespace std;
class Engine {
public:
int power;
};
class Car {
public:
//Engine e;
string company;
string color;
void show_details();
//void show_details() {
// cout << "Compnay is: " << company << endl;
// cout << "Color is: " << color << endl;
// cout << "Engine horse power is: " << e.power << endl;
//}
};
void Car::show_details(){
cout << "Compnay is: " << company << endl;
cout << "Color is: " << color << endl;
cout << "Engine horse power is: " << e.power << endl;
}
int main() {
Car c;
c.e.power = 500;
c.company = "hyundai";
c.color = "black";
c.show_details();
return 0;
}
g++ returns the following errors:
comp3.cpp: In member function ‘void Car::show_details()’:
comp3.cpp:22:44: error: ‘e’ was not declared in this scope
cout << "Engine horse power is: " << e.power << endl;
^
comp3.cpp: In function ‘int main()’:
comp3.cpp:26:9: error: ‘class Car’ has no member named ‘e’
c.e.power = 500;
I am clearly confused regarding issues of scoping, but I am not sure as to what the missing piece is.
Thanks for any & all help!!!

In the second example you commented out e.
//Engine e;

Related

Compiler Error - 'class Item' has no member named 'a' Line 46

#include<iostream>
#include<string>
using namespace std;
class Item{
private:
string type;
string abbrv;
string uID;
int aircraft;
double weight;
string destination;
public:
Item(string t, string a, string u, int aC, double w, string d){
type = t;
abbrv = a;
uID = u;
aircraft = aC;
weight = w;
destination = d;
}
Item(){}
Item(Item & i){
type = i.type;
abbrv = i.abbrv;
uID = i.uID;
aircraft = i.aircraft;
weight = i.weight;
destination = i.destination;
}
void print(){
cout << "ULD: " << type << endl;
cout << "Abbreviation: " << abbrv << endl;
cout << "ULD-ID: " << uID << endl;
cout << "Aircraft: " << aircraft << endl;
cout << "Weight: " << weight << " Kilograms" << endl;
cout << "Destination: " << destination << endl;
}
friend void kilotopound(Item);
};
void kilotopound(Item I){
cout<<"Weight in Pounds: " << I.weight * 2.2 << " LBS " << endl;
}
bool operator == (Item &ab, Item &bc){
if((ab.a == bc.a) && (ab.u == bc.u)){
return true;
}
else{
return false;
}
}
int main(){
Item I ("Pallet", "PAG32597IB", "PAG", 737, 3321, "SEA");
I.print();
kilotopound(I);
cout << "\nCopy\n\n";
Item I2(I);
I.print();
kilotopound(I);
cout<<"\nSecond Object\n\n";
I2.print();
kilotopound(I2);
Item unit1 ("Pallet", "PAG32597IB", "PAG", 737, 3321, "SEA");
Item unit2(unit1),unit3(I);
if (unit1 == unit2)
cout << "\nUnit1 and Unit2 are the same \n";
else
cout << " \nUnit1 and Unit2 aren't the same \n";
if (unit2 == unit3)
cout << " \nUnit2 and Unit3 are the same\n";
else
cout << " \nUnit2 and Unit3 aren't the same\n";
return 0;
}
Hi! So the code above gives me the error 'class Item' has no member named 'a' at line 46, which is where to bool operator is. Can someone help me out with basically just trying to get the code to function and explain why I get the error even though I have the data made public?
I'm pretty lost at why this happens even if the abbreviations are already stated. Also I tried just using abbrv and uID but got an error that the data was private.
Thank you!
a is the parameter of Item's constructor Item(string t, string a, string u, int aC, double w, string d), not an "alias" of Item::abbrv. Constructors are functions, and the parameters of a function are only available inside the function body.
There is no "member alias" in C++, nor is there any concept of "properties" (like in C#). To provide read-only access to Item::abbrv, define a "getter" function for it:
// Public member function of class Item:
const string& getAbbrv() const {
return abbrv;
}

Error Variable is Protected

#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
using namespace std;
void armySkirmish();
void battleOutcome();
string commander = "";
int numberOfHumans = 0;
int numberOfZombies = 0;
class ArmyValues
{
protected:
double attackPower;
double defensePower;
double healthPoints;
public:
void setAttackPower(double a)
{
attackPower = a;
}
void setDefensePower(double d)
{
defensePower = d;
}
void setHealthPoints(double h)
{
healthPoints = h * (defensePower * .1);
}
};
class Zombies: public ArmyValues
{
};
class Humans: public ArmyValues
{
};
int main(int argc, char ** argv)
{
cout << "Input Commander's Name: " << endl;
cin >> commander;
cout << "Enter Number of Human Warriors: " << endl;
cin >> numberOfHumans;
cout << "Enter Number of Zombie Warriors: " << endl;
cin >> numberOfZombies;
armySkirmish();
battleOutcome();
return 0;
}
void armySkirmish()
{
cout << "\nThe Humans tense as the sound of the undead shuffle towards them." << endl;
cout << commander << " shuffles forward with a determined look." << endl;
cout << "The undead form up into ranks and growl a war chant!" << endl;
cout << commander <<" shouts, CHARGE!!!" << endl;
cout << endl;
cout << "Warriors from both sides blitz across the field!" << endl;
cout << endl;
cout << "*The Carnage has begun!*" << endl;
cout << "*Steal, Sparks, and Flesh flies" << endl;
}
void battleOutcome()
{
int zombieLives = numberOfZombies;
int humanLives = numberOfHumans;
int randomNumber = 0;
int humanDeath = 0;
int zombieDeath = 0;
double newHumanLife = 0;
double newZombieLife = 0;
Zombies zombieBattleData;
Humans humanBattleData;
srand(time(NULL));
zombieBattleData.setAttackPower(20.0);
humanBattleData.setAttackPower(35.0);
zombieBattleData.setDefensePower(15.0);
humanBattleData.setDefensePower(20.0);
zombieBattleData.setHealthPoints(150.0);
humanBattleData.setHealthPoints(300.0);
while(zombieLives && humanLives > 0)
{
randomNumber = 1+(rand()%10);
if(randomNumber < 6)
{
newHumanLife = humanBattleData.healthPoints - zombieBattleData.attackPower;
if(newHumanLife <= 0)
{
humanLives--;
humanDeath++;
}
}else
{
newZombieLife = zombieBattleData.healthPoints - humanBattleData.attackPower;
if(newZombieLife <= 0)
{
zombieLives--;
zombieDeath++;
}
}
}
if(zombieLives <= 0)
{
cout << "Humans have emerged victorious!" << endl;
cout << "Human Deaths: " << humanDeath << "Zombie Deaths: " << zombieDeath << endl;
}else if(humanLives <= 0)
{
cout << "Zombies have emerges victorious!" << endl;
cout << "Human Deaths: " << humanDeath << "Zombie Deaths: " << zombieDeath << endl;
}
I know the code wont run properly as of now. What I was doing was a test run to make sure I was receiving no errors. The two errors I'm getting are:
armySimulatorMain.cpp:25:10: error: 'double ArmyValues::healthPoints' is protected
armySimulatorMain.cpp:115:67: error: within this context.
newHumanLife = humanBattleData.healthPoints - zombieBattleData.attackPower;
This is the case for Attack Power and Health Power however, Defense power is clearing the errors. i don't understand why they are getting flagged. I'm changing the variable through the public function so shouldn't this be allowed?
Also, I'm calling three variables outside of all functions because they are being used by multiple functions. How can I plug those variables somewhere I don't like that they are floating freely above everything?
Thanks guys I can't believe I forgot about getters... Anyway the code runs now much appreciated I'll make sure to remember this time xD
It's not complaining about the line where you set the values; as you say, that uses a public function. But here, you try to read the protected member variables:
newHumanLife = humanBattleData.healthPoints - zombieBattleData.attackPower;
You only try to read two variables, and those are the ones it complains about.
You'll need a public getter function to read the values.
You need to do something like:
public:
double gethealthPoints()
{
return healthPoints;
}
because attackPower, defensePower, healthPoints are all protected, so if you want to access to any of them you need a getter, otherwise you will always receive an protect error

No match for "operator<<" in std::operator

#include <iostream>
#include <string>
using namespace std;
// your code
class Dog {
public:
int age;
string name, race, voice;
Dog(int new_age,string new_name,string new_race,string new_voice);
void PrintInformation();
void Bark();
};
Dog::Dog(int new_age,string new_name,string new_race,string new_voice) {
age = new_age;
name = new_name;
race = new_race;
voice = new_voice;
}
void Dog::PrintInformation() {
cout << "Name: " << name;
cout << "\nAge: " << age;
cout << "\nRace: " << race << endl;
}
void Dog::Bark(){
cout << voice << endl;
}
int main()
{
Dog buffy(2, "Buffy", "Bulldog", "Hau!!!");
buffy.PrintInformation();
cout << "Dog says: " << buffy.Bark();
}
I'm newbie in C++ and I'm unable to figure out the error.I am getting the error at buffy.Bark(),it seems like its unable to print something which returns void.
no match for operator<< in std::operator<< >(&std::cout),((const char)
Either declare member function Bark like
std::string Dog::Bark(){
return voice;
}
and call it like
cout << "Dog says: " << buffy.Bark() << endl;
Or do not change the function but call it like
cout << "Dog says: ";
buffy.Bark();
because the function has return type void.
Or take another dog from the dog kennel.:)
Bark is defined as a void function:
void Dog::Bark(){
cout << voice << endl;
}
This means that trying to do cout << buffy.Bark() in main is trying to cout a void type variable, which is not possible. It's likely you simply meant buffy.Bark();, which will already output for you.

object oriented programming,use of static function to count objects

I want to display the objects of the class and the number of objects by using a static function. I typed this code but it does not work. It gives an error Too many types indeclaration" and "undefined symbol getCount. Can anyone help me? where is actually error in this code?
#include<iostream>
#include<string>
class Bag {
private:
static int objectCount;
int Weight;
std::string Brand;
std::string Type;
std::string Material;
std::string Colour;
public:
Bag(int W, std::string B, std::string T, std::string M, std::string C) {
Weight = W;
Brand = B;
Type = T;
Material = M;
Colour = C;
objectCount++;
}
void print() {
std::cout << "\n";
std::cout << "Bag: \n\n";
std::cout << "Weight:\t\t" << Weight << "kg" << '\n';
std::cout << "Brand:\t\t" << Brand << '\n' << "Type:\t\t" << Type << '\n';
std::cout << "Material:\t" << Material << '\n' << "colour:\t\t" << Colour << std::endl;
}
static int getCount() {
return objectCount;
}
};
int Bag::objectCount = 0;
int main() {
Bag bag_1(2, "Slazanger", "Atheletic Bag", "Polyethylene", "Brown");
bag_1.print();
std::cout << "object count " << Bag::getCount() << '\n';
Bag bag_2(4, "Samsonite", "Travel Bag", "Synthetic Fibre", "Gray");
bag_2.print();
std::cout << "object count " << Bag::getCount() << '\n';
Bag bag_3(5, "Herschel", "Duffel bag", "Leather", "Black");
bag_3.print();
std::cout << "object count " << Bag::getCount() << '\n';
Bag bag_4(3, "Kewin Woods", "Hand Bag", "Fibre", "Blue");
bag_4.print();
std::cout << "object count " << Bag::getCount() << std::endl;
while(!std::cin.get());
return 0;
}
You are scoping it incorrectly, getCount is statically scoped to the translation
unit, not the class. Thus it has no symbol named objectCount available to it.
To fix it, merely put the method inside the class.
class Bag {
private:
static int objectCount;
int Weight;
string Brand,Type,Material,Colour;
public:
Bag(int W ,string B ,string T,string M,string C)
{
Weight=W;
Brand=B;
Type=T;
Material=M;
Colour=C;
objectCount++;
}
void print()
{
cout<<"\n";
cout<<"Bag: \n\n";
cout<<"Weight:\t\t"<<Weight<<"kg"<<endl;
cout<<"Brand:\t\t"<<Brand<<endl<<"Type:\t\t"<<Type<<endl;
cout<<"Material:\t"<<Material<<endl<<"colour:\t\t"<<Colour<<endl;
}
static int getCount()
{
cout<< objectCount;
}
};
Aditionally, Borland is a really old compiler and suprised to even still
hear it's name, last release was around 15 years ago so you should really
consider using clang, gcc or msvc and upgrading your learning materials to
something less ancient. There has been alot of evolution in terms of practices,
standards and compiler conformance.
For example, C++ headers don't have an extension, and other small things like that.
This is a working version of your code:
#include <iostream>
#include <cstring>
using namespace std;
class Bag {
private:
static int objectCount;
int Weight;
string Brand, Type, Material, Colour;
public:
Bag(int W, string B, string T, string M, string C) //constructor
{
Weight = W;
Brand = B;
Type = T;
Material = M;
Colour = C;
objectCount++;
}
void print() {
cout << "\n";
cout << "Bag: \n\n";
cout << "Weight:\t\t" << Weight << "kg" << endl;
cout << "Brand:\t\t" << Brand << endl << "Type:\t\t" << Type << endl;
cout << "Material:\t" << Material << endl << "colour:\t\t" << Colour
<< endl;
}
static int getCount() //static function to count objects
{
cout << objectCount;
};
};
int Bag::objectCount = 0;
int main() {
Bag bag_1(2, "Slazanger", "Atheletic Bag", "Polyethylene", "Brown");
Bag bag_2(4, "Samsonite", "Travel Bag", "Synthetic Fibre", "Gray");
Bag bag_3(5, "Herschel", "Duffel bag", "Leather", "Black");
Bag bag_4(3, "Kewin Woods", "Hand Bag", "Fibre", "Blue");
bag_1.print();
cout << "object count" << Bag::getCount();
bag_2.print();
cout << "object count" << Bag::getCount();
bag_3.print();
cout << "object count" << Bag::getCount();
bag_4.print();
cout << "object count" << Bag::getCount();
}
There were several mistakes in the version you posted:
in C++ you don't need the .h when including files
you were using cout without the std:: qualifier or adding using namespace std; to your source. Also, please read this.
your static function was not declared/defined inside your class definition
it should be int main instead of void main
One last note: I removed your #include <conio.h> which should probably read #include <conio> and getch because I compiled this on a linux machine. Feel free to add them back in if you want them.

Classes(Odometer)- Error Message

I was wondering if anyone could give me a clue as to what these error messages mean when I try to compile my code.
Here is the error I get:
in function 'int main()':
not match for 'operator<<'in 'std::operator<<[with_Traits = std::char_traits(((std::basic_ostr...
and it repeats for a while.
I want to post my full code just so you have a idea of what my assignment is, it not that long! =)
#include <iostream>
#include <cstdlib>
using namespace std;
class Odometer
{
public:
Odometer();
void reset();
void totalfuel();
void input_miles(int getmiles);
void Odometer::set_fuel_efficiency(double fuel_efficiency);
int gallonsUsed;
private:
int milesDriven;
double fuel_efficiency;
int getmiles;
};
Odometer::Odometer()
{
milesDriven = 0;
fuel_efficiency = 0;
}
void Odometer::reset()
{
milesDriven = 0;
}
void Odometer::totalfuel()
{
fuel_efficiency = (milesDriven/gallonsUsed);
}
void Odometer::input_miles(int miles_driven)
{
milesDriven = milesDriven + miles_driven;
}
void Odometer::set_fuel_efficiency(double Fuel_efficiency)
{
fuel_efficiency = Fuel_efficiency;
}
double Odometer::getgallons()
{
return milesDriven/fuel_efficiency;
}
// ======================
// main function
// ======================
int main()
{
// Two test trips
Odometer trip1, trip2;
trip1.reset();
trip1.set_fuel_efficiency(45);
trip1.input_miles(100);
cout << "For your fuel-efficient small car:" << endl;
cout << "After 100 miles, " << trip1.totalfuel() << " gallons used." << endl;
trip1.input_miles(50);
cout << "After another 50 miles, " << trip1.totalfuel() << " gallons used." << endl;
trip2.reset();
trip2.set_fuel_efficiency(13);
trip2.input_miles(100);
cout << "For your gas guzzler:" << endl;
cout << "After 100 miles, " << trip2.totalfuel() << " gallons used." << endl;
trip2.input_miles(50);
cout << "After another 50 miles, " << trip2.totalfuel() << " gallons used." << endl;
system("PAUSE");
return 0;
}
What would you expect cout << void to print?
totalfuel() returns void, and you're passing it as a parameter to cout::operator <<. Did you mean to return something from the method?
Perhaps:
double Odometer::totalfuel()
{
fuel_efficiency = (milesDriven/gallonsUsed);
return fuel_efficiency;
}
totalFuel() returns void. I think you meant to invoke the getgallons() method instead.