C++ How to implement this code into the heap properly - c++

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!

Related

"undefined identifier" despite defining it in the class.

im a beginner in c++ and i am so confused why i am getting an error in my code, could you guys please tell me whats going wrong? im using visual studios 2017.
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
class Cat {
private:
bool happy;
public:
void speak() {
cout << "meow" << endl;
}
Cat() {
bool newHappy = happy;
happy = true;
}
};
int main()
{
cout << "Starting program..." << endl;
Cat bob;
bob.speak();
if (happy) {
cout << "cat is happy" << endl;
}
else {
cout << "unhappy cat" << endl;
}
cout << "Ending program..." << endl;
return 0;
}
You're trying to reference a variable called happy inside your main function, which doesn't exist in that scope. If you want to see if bob is happy, you could simply write if (bob.happy){ ... and change Cat::happy from private to public, or you could create a getter function like:
class Cat {
private:
bool happy;
public:
bool isHappy() const {
return happy;
}
...
};
and call the function as follows: if (bob.isHappy()){ ...

How do I get my constructor and functions to work so my main() is able to display both the string and int data?

I am learning about functions and classes, and wrote my own code. I used the constructor to just initialize the variables. I have a function that is supposed to get the info I initialized with the constructor and allow me to display it. However, it doesn't want to work. I am not really sure what I am doing wrong. My error code says that I have unresolved externals because of my "void" function. I thought my function was not returning anything but rather just displaying the input it got from the initialization of the constructor.
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
class Berries {
string Nameofberries;
int Price;
public:
Berries (string N,int B)
{
Nameofberries = N;
Price = B;
}
void GetBerryInfo(const Berries& B)
{
cout << B.Nameofberries << endl;
cout << B.Price << endl;
}
};
void GetBerryInfo (const Berries& B);
int main ()
{
Berries Berryinfo1( "Raspberries", 7);
cout << GetBerryInfo;
system("pause");
return 0;
}
There are several mistakes.
void GetBerryInfo(const Berries& B)
{
cout << B.Nameofberries << endl;
cout << B.Price << endl;
}
should be
void GetBerryInfo()
{
cout << Nameofberries << endl;
cout << Price << endl;
}
==================================================================
void GetBerryInfo (const Berries& B);
should be removed.
==================================================================
cout << GetBerryInfo;
should be
Berryinfo1.GetBerryInfo();
==================================================================
All computer langauges are fussy, you have to get the details right, as well as understand the concepts.
This will do what you wanted:
# include <iostream>
# include <iomanip>
# include <string>
using namespace std;
class Berries {
string Nameofberries;
int Price;
public:
Berries (string N,int B)
{
Nameofberries = N;
Price = B;
}
void GetBerryInfo()
{
cout << Nameofberries << endl;
cout << Price << endl;
}
};
int main ()
{
Berries Berryinfo1( "Raspberries", 7);
Berryinfo1.GetBerryInfo();
system("pause");
return 0;
}
A couple of points on your mistakes:
GetBerryInfo() was declared inside the class. You don't need to re-declare it in the global scope. That 2nd declaration should be removed.
To be invoked, functions (like GetBerryInfo) must have () at the end of them like so: GetBerryInfo().
There is no point for GetBerryInfo() to take Berries as a paremeter. It is a member function that is part of the class Berries. It has access to all data members of a Berries instance already.
You don't need to use cout here: cout << GetBerryInfo; because the function body already sends the data members to cout. This function returns void so it doesn't make sense to send this to cout anyway.

Setting string name in main function only using getName

I am working on an assignment using sub classes demonstrating polymorphism. This program requires a name to be given for each of the new objects. I am only supposed to have string getName(){return name;} (this is located in the base class). There is also a constructor in each of the classes class(string){}. In the main function I want to set the name for each of the objects. Any advice is much appreciated in how I should do so!
h file:
#ifndef DUCK_H
#define DUCK_H
#include <string>
using namespace std;
class Duck
{
private:
string name;
public:
Duck(){}
Duck(string){}
string getName() { return name; };
virtual string quack() {return "Which"; }
virtual string fly() { return "How?"; }
};
class RubberDuck : public Duck
{
public:
RubberDuck(){}
RubberDuck(string) {}
string quack() { return "Squeak"; }
string fly() { return "Fly with bounce"; }
};
class MallardDuck : public Duck
{
public:
MallardDuck(){}
MallardDuck(string) {}
string quack() { return "Quack"; }
string fly() { return "Fly with wings"; }
};
class RocketDuck : public Duck
{
public:
RocketDuck(){}
RocketDuck(string) {}
string quack() { return "Zoom"; }
string fly() { return "Fly with rockets"; }
};
#endif // !1
cpp file:
#include <iostream>
#include "Duck.h"
using namespace std;
//void display(Duck *d);
int main()
{
Duck d1;
MallardDuck md;
RubberDuck rbd;
RocketDuck rd;
//for main duck
//Duck duck("Donald");
//cout << duck.getName();
cout << d1.quack() <<"\n";
cout << d1.fly() <<"\n";
cout << "\n";
//for rubber duck
RubberDuck rbdname("Rubby");
cout << rbd.quack() << "\n";
cout << rbd.fly() << "\n";
cout << "\n";
//for mallard duck
MallardDuck mdname("Mally");
cout << md.quack() << "\n";
cout << md.fly() << "\n";
cout << "\n";
// for rocket duck
RocketDuck rdname("Rocky");
cout << rd.quack() << "\n";
cout << rd.fly() << "\n";
cout << "\n";
//polymorphism
Duck *d2 = new MallardDuck();
cout << d2->getName() << "\n";
cout << d2->quack() << "\n";
cout << d2->fly() << "\n";
cout << "\n";
return 0;
}
/*void display(Duck d)
{
cout << d.quack();
}
*/
Are you asking how to call the constructor you've defined? You would do that like
Duck duck("Drake Mallard");
With this code:
Duck(){}
Duck(string){}
You don't initialize your member name, whether you call the default constructor or the string one.
You have to use the input parameter like I showed you:
Duck(string const & input_name) : name(input_name) {}
^^^^^^^^^^^^^^^^
The underlined part initializes your member name to the value "Drake Mallard" when you do:
Duck duck("Drake Mallard");
Then, you will have duck.getName() returning "Drake Mallard".
And you have to apply the same principle in your derived classes, to call this very same base constructor:
class RubberDuck : public Duck
{
public:
RubberDuck() : Duck("RubberDuck") {}
RubberDuck(string const & input_name) : Duck(input_name) {}
Then
RubberDuck rubber; // name = "RubberDuck"
RubberDuck rubber("Ruber"); // name = "Rubber"
But also:
RubberDuck * rubber = new RubberDuck(); // name = "RubberDuck"
RubberDuck * rubber = new RubberDuck("Ruber"); // name = "Rubber"
If you ask, the front part Duck:: in my comment considered you where implementing your constructor outside of class Duck { ... };.
You should avoid using namespace, especially within headers.

Cannot call function of a class from main

#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.

C++ Inheritance problem

I hope I got the relevant code in here. I have some problem when I want to fetch the menu option that I've added into to menu_1. I have this function on_select(int) that I use to fetch one sub-menu's options, which I do by using the display() function. But when I compile it will say that there are no function named display() in menu_option() class, which is the Base class, but what I want to is to access the display() function which is located in the sub_menu() class.
I have tried multiple thing to get the relevant object from the array without any success, so I'm here now asking for help with this one.
I have this following main()
#include <iostream>
using namespace std;
#include "menu.h"
int main()
{
sub_menu* main_menu = new sub_menu("Warehouse Store Menu");
sub_menu* menu_1 = new sub_menu("Menu1");
main_menu->add_option(new sub_menu("Menu2"));
main_menu->add_option(menu_1);
product_menu->add_option(new add_item("sub_item1"));
product_menu->add_option(new add_item("sub_item2"));
product_menu->add_option(new add_item("sub_item3"));
main_menu->display();
main_menu->on_select(1);
delete main_menu;
return 0;
}
header file
#include <iomanip>
#include <iostream>
#include <string>
using namespace std;
const int MAX_SIZE = 9;
class menu_option
{
public:
menu_option(string const& n) : title(n) {};
virtual ~menu_option();
virtual void on_select(int) = 0;
string get_title() { return title; }
protected:
string title;
};
/* ------------------------------------- */
class sub_menu : public menu_option
{
public:
sub_menu(string const& n)
: menu_option(n) { no_item = 0; }
~sub_menu() { delete[] list; };
void on_select(int);
void add_option(menu_option*);
void display();
private:
menu_option* list[MAX_SIZE]; //container for options in the sub_menu
int no_item;
};
implement file
void sub_menu::on_select(int i)
{
cout << (list[i])->get_title() << endl;
cout << (list[i])->display() << endl; //<------ Doesn't work
}
void sub_menu::add_option(menu_option* item)
{
list[no_item] = item;
no_item++;
}
void sub_menu::display()
{
cout << ">> " << get_title() << " <<"<< endl;
for( int i = 0; i < no_item; i++ )
{
cout << setw(2) << i << ": " << (list[i])->get_title() << endl;
}
}
You can do what you want to do, but it's bad. You have to cast down to sub_menu when you call display() in on_select(). Of course it's not going to work the way you have it, and the compiler is telling you exactly why.
The other option, which is probably better (though without a clear understanding of the problem space may not be the best) would be to add display() as a virtual function to the menu_option class.
To solve your immediate problem you'll want to use dynamic_cast to turn a menu_option* into a sub_menu*, like so:
sub_menu* submenu(dynamic_cast<sub_menu*>(list[i]));
Note that if the cast fails (i.e., the menu_option pointed to by list[i] is not a sub_menu after all) the value of the submenu pointer will be NULL, so make sure you check that it is a valid pointer before using it in subsequent code.