Hi StackOverflow community!
I'm expecting different outputs depending on the class of object to be printed but that's not the case.
Medium.h
#include "Datum.h"
#include "Person.h"
class Medium
{
public:
Medium(std::string initTitel);
virtual ~Medium(void);
void ausgabe() const;
bool ausleihen(Person person, Datum ausleihdatum);
void zurueckgeben();
unsigned int getID();
protected:
static unsigned int currentID;
unsigned int ID;
std::string titel;
bool status;
Datum datumAusgeliehen;
Person personAusgeliehen;
};
Medium.cpp
#include "Medium.h"
#include <string>
#include <iostream>
unsigned int Medium::currentID = 1;
Medium::Medium(std::string initTitel): titel(initTitel), status(false)
{
ID = currentID++;
}
Medium::~Medium(void) {}
void Medium::ausgabe() const
{
std::cout << "ID: " << ID << std::endl;
std::cout << "Titel: " << titel << std::endl;
switch (status)
{
case true:
std::cout << "Status : Das Medium ist seit dem "
<< datumAusgeliehen << " an "
<< personAusgeliehen.getName() << " ausgeliehen."
<< std::endl;
break;
case false:
std::cout << "Status: Medium ist zurzeit nicht verliehen." << std::endl;
break;
}
}
The function prints ID, title and status to console.
Now depending on the type of Medium, I would like to print extra information using the function void ausgabe() const.
Example: If the Medium is a book(in german buch = book), information about author should be printed, in addition to other information available in Medium class. i.e, I have got the subclass called Buch which also has an void ausgabe() const function, which should print this extra information in class Buch.
Buch.h
#include "Medium.h"
class Buch: public Medium
{
public:
Buch();
Buch(std::string initTitel, std::string initAutor);
virtual ~Buch();
void ausgabe() const;
private:
std::string autor;
};
Buch.cpp
#include "Buch.h"
Buch::Buch(std::string initTitel, std::string initAutor): Medium(initTitel), autor(initAutor)
{ // TODO Auto-generated constructor stub }
Buch::~Buch() { // TODO Auto-generated destructor stub }
void Buch::ausgabe() const
{
Medium::ausgabe();
std::cout << "Autor: " << autor << std::endl;
}
As far as I have: In the class Buch, while calling the output function ausgabe() the extra information autor will be printed automatically. But for the remaining informations from Medium class, could you help. Thanks for your help :)
Now depending on the type of Medium to be printed, I would like to add
extra information to be printed. E.g. if the Medium is a book,
information about author should be printed too.
So you are looking for dynamic-polymorphism. Then, you need to make void ausgabe()const function to virtual in your base class(Medium), in order to call it polymorphically. And you need to override it in other subclasses(for instance class Buch). In the given code anyways these are not there. In addition to that, you also need virtual destructor at your base class.
Then in your class Buch's ausgabe() should be:
void ausgabe()const override
{
Medium::ausgabe(); // call first base class's ausgabe()
std::cout << "autor :" << autor << std::endl;
}
Then in your main, you can do this: See an example code here
int main ()
{
std::unique_ptr<Medium> some_objects[2];
some_objects[0] = std::make_unique<Medium>("Some Title");
some_objects[1] = std::make_unique<Buch>("Title 2", "user9775960");
for(auto& obj_type: some_objects)
obj_type->ausgabe();
return 0;
}
PS: always try to post English written code in the community, so that everybody can follow.
Related
We're learning about constructors in class and I was trying to experiment with an overloaded constructor. When I run my program I keep getting an error written in the color red that says...
~
The ampersand (&) character is not allowed. The & operator is reserved for future use; wrap an ampersand in double quotation marks ("&") to pass it as part of a string.
^This only happens when I try to use private variables, when everything is public nothing goes wrong.
///Here's my code
#include <iostream>
using namespace std;
class JCole {
private:
string song;
string album;
int albumNum;
JCole::JCole(string _song, string _album, int _Num) {
song = _song;
album = _album;
albumNum = _Num;
}
};
int main() {
JCole album1("Punchin the clock", "The Off-Season", 6);
JCole album2("ATM","KOD",5);
cout << album1.song << " " << album1.album << " " << album1.albumNum << endl;
cout << album2.song << " " << album2.album << " " << album2.albumNum << endl;
return 0;
}
Your constructor is declared as private because you haven't changed the access setting.
Try this:
class JCole {
private:
string song;
string album;
int albumNum;
// Insert:
public:
JCole::JCole(string _song, string _album, int _Num) {
song = _song;
album = _album;
albumNum = _Num;
}
};
A private constructor is a nasty thing; only members of the class can call it. Thus wreaking havoc with external code that wants to instantiate this class.
Also, you can use many public:, private:, protected: within your class and in any order.
I am working on a class assignment to create three classes nested inside each other. I need to make constructors and deconstructors for each that have a message that goes along with them. Finally, I need to create an instance of each class using new and call the display() function to show their message, followed by delete.
I have completed the assignment but in the wrong way, and I am confused about how I can properly put the code into the heap instead of the stack (as I was advised by my course tutor).
This is what I started with: (this code seems to work well, but does not fulfill the assigned project)
#include <string>
#include <iostream>
#include <fstream>
using namespace std;
class Hen {
public:
Hen();
~Hen();
string display(void) {
return ("Im a Hen");
}
class Nest;
friend Nest;
class Nest {
public:
Nest();
~Nest();
string display(void) {
return ("Im a Nest");
}
class Egg;
friend Egg;
class Egg {
public:
Egg();
~Egg();
string display(void) {
return ("Im an egg");
}
};
};
};
Hen::Hen() {
cout << "I construct Hens" << endl;
}
Hen::~Hen() {
cout << "I deconstruct Hens" << endl;
}
Hen::Nest::Nest() {
cout << "I construct Nests" << endl;
}
Hen::Nest::~Nest() {
cout << "I deconstruct Nests" << endl;
}
Hen::Nest::Egg::Egg() {
cout << "I construct Eggs" << endl;
}
Hen::Nest::Egg::~Egg() {
cout << "I deconstruct Eggs" << endl;
}
int main() {
Hen hone;
Hen::Nest none;
Hen::Nest::Egg eone;
string h, n, e;
h = hone.display();
n = none.display();
e = eone.display();
cout << h << "\n" << n << "\n" << e << endl;
}
Where I am stuck is when I try to implement my code inside the heap, it seems to break by the second class:
#include <string>
#include <iostream>
#include <fstream>
using namespace std;
class Hen {
public:
void display() {
cout << "Im a Hen" << endl;
}
class Nest;
friend Nest;
class Nest {
public:
void display() {
cout << "Im a Nest" << endl;
}
class Egg;
friend Egg;
class Egg {
public:
void display() {
cout << "Im an egg" << endl;
}
};
};
};
int main() {
Hen *hone = new Hen();
Hen::Nest *none = new Nest();
hone -> display();
none -> display();
}
Question 1:
If I remove all the information related to nest, the program runs Hen just fine and returns the "I'm a hen" statement. But, when I add in nest, the warning I recieve is
"error: expeected type-specifier before 'Nest'
Hen::Nest *none = new Nest();"
I do not understand what I am doing wrong as I did the exact same process for Hen and it worked. I do know that the error must be in the way Nest gets called through hen?
I apologize if this question is obvious, but I am just starting c++ and do not understand why I am getting these messages...
Thanks for your help!
I'm trying to understand virtual classes in C++. In Wikipedia, I found this example:
#include <iostream>
class Machine {
public:
void run() { }
class Parts {
public:
virtual int get_wheels() = 0;
virtual std::string get_fuel_type() = 0;
};
};
// The inner class "Parts" of the class "Machine" may return the number of wheels the machine has.
class Car: Machine {
public:
void run() {
std::cout << "The car is running." << std::endl;
}
class Parts: Machine::Parts {
public:
int get_wheels() override {
std::cout << "A car has 4 wheels." << std::endl;
return 4;
}
std::string get_fuel_type() override {
std::cout << "A car uses gasoline for fuel." << std::endl;
return "gasoline";
}
};
};
I can get the number of wheels of a car with:
Car::Parts c_p;
c_p.get_wheels();
Is there any other (simple) way? Is there any way instantiating only Car car ?
Update:
I understand the concerns, but I find it useful as a nested interface (with minimal changes):
#include <iostream>
#include <memory>
class Machine {
public:
virtual void run() = 0;
class Parts {
public:
virtual int get_wheels() = 0;
virtual std::string get_fuel_type() = 0;
};
};
class Car: public Machine {
public:
void run() {
std::cout << "The car is running." << std::endl;
}
class Parts: public Machine::Parts {
public:
int get_wheels() override {
std::cout << "A car has 4 wheels." << std::endl;
return 4;
}
std::string get_fuel_type() override {
std::cout << "A car uses gasoline for fuel." << std::endl;
return "gasoline";
}
};
};
int main () {
std::shared_ptr<Machine> X = std::make_shared<Car>();
(*X).run();
std::shared_ptr<Machine::Parts> Y = std::make_shared<Car::Parts>();
(*Y).get_wheels();
return 0;
}
I don't find any other code with this functionality. The only thing I miss is the possibility to access get_wheels directly from X. For instance, let's consider that I have a Machine in my program. The kind of machine I have will be specified dynamically. I want to know the number of wheels of this machine, but the method get_wheels must be inside a nested class Parts. The closer to solve this problem that I've got is with the code above, which gives me Machine and Machine::Parts as interfaces.
A simple solution would be to have a member part of you car:
struct Car : Machine {
struct Parts : Machine::Parts {
int get_wheels() override {
std::cout << "A car has 4 wheels." << std::endl;
return 4;
}
std::string get_fuel_type() override {
std::cout << "A car uses gasoline for fuel." << std::endl;
return "gasoline";
}
} parts; // <---
// or declare it as a separated member:
// Parts parts;
};
That way, you can call member functions like this:
Car car;
std::cout << car.parts.get_weels();
No. As it stands, a Car instance does not have any Car::Parts instances, nor any method that returns one.
The text around the example seems to be assuming that there is an instance of Machine::Parts associated with Machine somehow, which magically becomes a Car::Parts in Car. This may be the case in some other language, but it is not the case in C++.
A much more idomatic design would be to have a traits class template that Machine subclasses specialise.
template <typename Machine>
struct MachineParts;
template <>
struct MachineParts<Car> {
static int get_wheels() {
std::cout << "A car has 4 wheels." << std::endl;
return 4;
}
static std::string get_fuel_type() {
std::cout << "A car uses gasoline for fuel." << std::endl;
return "gasoline";
}
};
template <>
struct MachineParts<Bicycle> {
static int get_wheels() {
std::cout << "A bike has 2 wheels." << std::endl;
return 2;
}
static std::string get_fuel_type() {
std::cout << "A bike uses muscles for fuel." << std::endl;
return "muscles";
}
};
#include <iostream>
#include <string>
using namespace std;
// my code starts
class Cat {
public:
int age;
string name, race, voice;
Cat(int age2,string name2,string race2,string voice2);
void PrintInformation();
};
Cat::Cat(int age2,string name2,string race2,string voice2) {
age = age2;
name = name2;
race = race2;
voice = voice2;
}
Cat::Meow(){
cout << "Cat says: " << fluffy.Meow() << endl;
}
void Cat::PrintInformation() {
cout << "Name: " << name;
cout << "\nAge: " << age;
cout << "\nRace: " << race << endl;
}
// my code ends
int main()
{
Cat fluffy(2, "Fluffy", "Bombay", "Meoow!!!");
fluffy.PrintInformation();
cout << "Cat says: " << fluffy.Meow();
}
I can't seem to figure out how to make this code work. My main problems seems to be that i don't know how to call fluffy.Meow(); from int main().
Thanks, for any help!
You forgot to declare Cat::Meow in the class declaration.
//some code
void PrintInformation();
void Meow();
Additionally, you have to specify what the return type of the function Meow is, in your case it would be void, because it returns nothing.
You also have some recursion going on, Meow calling Meow (forgetting about the fact that fluffy isn't a variable in this scope). Your Cat class knows nothing about the instance fluffy, so you can't access it.
I guess you meant voice instead.
I stumbled across this piece of code when I researched for a good example for Observer Design pattern. In main, it gets error, taking address of temporary[-fpermissive] which I dont dont understand what it is frankly. Sending a class refference to an function? Is this real life?
#include <vector>
#include <iostream>
using namespace std;
class AlarmListener
{
public:
virtual void alarm() = 0;
};
class SensorSystem
{
vector < AlarmListener * > listeners;
public:
void attach(AlarmListener *al)
{
listeners.push_back(al);
}
void soundTheAlarm()
{
for (int i = 0; i < listeners.size(); i++)
listeners[i]->alarm();
}
};
class Lighting: public AlarmListener
{
public:
/*virtual*/void alarm()
{
cout << "lights up" << '\n';
}
};
class Gates: public AlarmListener
{
public:
/*virtual*/void alarm()
{
cout << "gates close" << '\n';
}
};
class CheckList
{
virtual void localize()
{
cout << " establish a perimeter" << '\n';
}
virtual void isolate()
{
cout << " isolate the grid" << '\n';
}
virtual void identify()
{
cout << " identify the source" << '\n';
}
public:
void byTheNumbers()
{
// Template Method design pattern
localize();
isolate();
identify();
}
};
// class inheri. // type inheritance
class Surveillance: public CheckList, public AlarmListener
{
/*virtual*/void isolate()
{
cout << " train the cameras" << '\n';
}
public:
/*virtual*/void alarm()
{
cout << "Surveillance - by the numbers:" << '\n';
byTheNumbers();
}
};
int main()
{
SensorSystem ss;
ss.attach(&Gates());
ss.attach(&Lighting());
ss.attach(&Surveillance());
ss.soundTheAlarm();
}
This is ill-formed:
ss.attach(&Gates());
^^^
Gates() is an rvalue (specifically, a prvalue). You cannot take the address of an rvalue. It's not an object that has identity, so it doesn't really have an address that you can take. The language is preventing you from doing something that doesn't make sense to do. If you did store a pointer to this temporary, you'd just end up with a dangling pointer since at the end of this line the temporary Gates would be destroyed.
Since SensorSystem doesn't own its AlarmListeners, you'll have to create them up front:
Gates gates;
Lighting lighting;
Surveillance surveillance;
SensorSystem ss;
ss.attach(&gates);
ss.attach(&lighting);
ss.attach(&surveillance);