Need help printing out a string - c++

Im currently learning about classes in C++. Im coming from a java language background.
I have a class called animals. the animals constructor has a parameter in which a string is required. When i create an object of that class and try to print out the string that was passed to the constructor, it doesn't print out anything apart from a new line..
ANIMAL CLASS
#include "animal.h"
#include <string>
#include <iostream>
using namespace std;
animal::animal(string nameofanimal)
{
string name = nameofanimal;
}
void animal::getName(){
cout << name << endl;
}
ANIMAL HEADER:
#pragma once
#ifndef ANIMAL_H
#define ANIMAL_H
#include <string>
#include <iostream>
using namespace std;
class animal
{
private:
string name;
public:
animal(string x);
void getName();
};
#endif ANIMAL_H
MAIN CLASS
#include "animal.h"
#include <string>
#include <iostream>
using namespace std;
int main()
{
animal firstAnimal("Bob");
firstAnimal.getName();
}
the output is nothing. this is a very basic code and honestly cant believe I don't know how to do such a simple task. What I have noticed is that whenever I highlight the name varible in the animals constructor, the varible name in the getName() function doesn't highlight so im guessing this has something to do with pointers... I may be wrong though...

Change your animal constructor definition as follows
animal::animal(string nameofanimal) : name(nameofanimal) {
}
In your original definiton you have a local variable name that shadows the class member variable:
animal::animal(string nameofanimal)
{
string name = nameofanimal; // <<< This sets only the local variable
}

The problem is you are storing value in local variable
string name = nameofanimal;
while the value is not stored in actual data member of the class. To store it in data member use the following:
name = nameofanimal;

Related

C++ Invalid New Expression Of Abstract Class Type

I get this error when using c++. I tried other solutions such as using a shared pointer but with no avail. Here is my code :
Main.cpp:
int main() {
game_init();
cout << items.at(0).name << endl;
while(true) game_tick();
return 0;
}
Item.h:
#ifndef ITEM_H
#define ITEM_H
#include "../Rooms/Room.h"
#include <string>
#include <vector>
#include <memory>
using namespace std;
class Item {
public :
Room location;
string name, desc;
//Item(string, string, Room);
virtual void use() = 0;
};
vector <Item> items;
/*
Item::Item(string in_name, string in_desc, Room in_location) {
name = in_name;
desc = in_desc;
location = in_location;
}*/
#endif
Items.h:
#ifndef ITEMS_H
#define ITEMS_H
#include "OldKey.h"
#include <memory>
#include <vector>
vector <shared_ptr<Item>> all_items;
OldKey old_key;
void items_init() {
items.push_back(old_key);
}
#endif
The error is Invalid New Expression of Abstract class Type "Item". Hope I can fix this, keep in mind I am new to c++ so please try to explain the solution or workaround simply, thanks.
You are trying to instantiate a class (Item) with a pure virtual function (use). This is not allowed. To fix this you could
Create a subclass that implements the use function and then instantiate that subclass instead of Item.
Make the function virtual but not pure virtual, i.e., remove the = 0 and then provide a default implementation in the Item class. A subclass can then provide its own implementation of use by overriding the function.
Note that your definition of vector<Item> items looks fishy. If you attempt to store a subclass of Item in this vector then this will be converted to an instance of Item and all information of the subclass will be lost. You may want to change this to a vector of pointers, for example.

trouble with accessing a class from a different class

just started to learn c++.I'm trying new things in c++ on thing i wanted to try is to access a class from another class and change its instances and print its instance on screen.
I would like to know 2 things 1)whats wrong with my code 2)where should i declare class declarations (in main file or class definition file?)
here is the error log -
'object::carrier' uses undefined class 'sub'
'cout': is not a member of 'std'
'cout': undeclared identifier
this is what i came up with-
source.h
#include <iostream>
#include <vector>
#include "stuff.h"
int main()
{
object spoon(3);
spoon.get();
}
stuff.cpp
#pragma once
#include <vector>
class object;
class sub;
class object
{
private:
std::vector <sub> thing;
public:
object(int n);
void get() const;
};
class sub
{
private:
int num;
public:
void set_num(int n);
};
stuff.cpp
#include <vector>
#include "stuff.h"
// methods for object
object::object(int n)
{
sub carrier;
carrier.set_num(n);
}
void object::get() const
{
std::cout << carrier.num;
}
// methods for sub
void sub::set_num(int temp_num)
{
num = temp_num;
}
thanks
In your object class, specifically object::get definitions, you use the variable carrier without it being in scope.
When you declare the variable sub carrier in your constructor, it is only accessible in the same scope, that is, inside the constructor. Once your program leaves the scope, the variable carrier is deallocated (deleted).
You must add the variable sub carrier as a member to your class like so:
class object
{
private:
sub carrier
// other stuff
}
Edit:
I so you edited your question.
You must either replace cout with std::cout because cout is part of the c++ standard library. Alternatively, a less verbose option would be to add using namespace std; at the top of every .cpp file. This basically tells the compiler that you can use the namespace std without explicitly saying it. But don't do it for .h files. It's not a good idea.

Cannot create multiple instances of a class?

My problem is that i want to create multiple instances of my upgrade class, for different upgrades. Maybe it's because i'm used to java but i can't just type Source first("first"), second("second"); because if i do and call first.getName() for example, i get "second". I made an example file where i only wrote what i'm struggling with, so you don't have to try to understand my mess of a code.
Source.cpp: I want multiple instances of this class.
#include "Source.h"
std::string name;
Source::Source()
{
}
Source::Source(std::string nameToSet)
{
name = nameToSet;
}
std::string Source::getName()
{
return name;
Source.h
#pragma once
#include <string>
class Source {
public:
Source();
Source(std::string namel);
std::string getName();
};
Test.cpp
#include "Source.h"
#include "iostream"
Source first("first"), second("second");
int main()
{
std::cout << first.getName() << std::endl;
}
Output: second
Test.h
#pragma once
#include <string>
The problem is with this line:
std::string name;
This declares a single global string named name. This variable is not associated with any Source instance. Instead, you need to declare a field inside the Source class:
class Source {
public:
Source();
Source(std::string namel);
std::string getName();
// Add these two lines
private:
std::string name;
};
This will give a name for each Source. I suggest you study about class fields and the differences between public and private access.
add std::string name in your header file like that:
#pragma once
#include <string>
class Source {
private:
std::string name;
public:
Source();
Source(std::string namel);
std::string getName();
};
by this, everytime you call the constructor, "name" will be initiated to a single value that refers to your specific instance (first, second, etc).

C++: Error with 'this' keyword

I am attempting to create an poptart vending machine program within c++ and i am trying to use the this keyword, however i am always getting an error stating 'this' may only be used inside a nonstatic member function. Below is a part of the code that i am getting one such issue in
Code:
#include <iostream>
#include "HasCredit.h"
using namespace std;
void insertMoney(int money)
{
cout<<"You inserted: " << money;
money = money+this->currentContext->getStateParam(Credit);
this->currentContext->setStateParam(Credit,money);
cout<< "Total: "<<money<<endl;
this->currentContext->setState(Has_Credit);
}
Any suggestions onto why i am getting this error will be most appreciated. Cheers.
Edit: the insertMoney method is within a class called HasCredit.
Edit2: member declarations are now made outside of the constructor
Edit3: Added state class declaration
The Class Definition Code is Below:
#include <iostream>
#include "State.h"
#include "StateContext.h"
using namespace std;
class HasCredit: public State
{
HasCredit (StateContext* Context) : State(Context) {
}
void insertMoney(int);
void MakeSelectionCoating(int);
void MakeSelectionFilling(int);
void moneyRejected(void);
void addPopTarts(int);
void dispense(void);
};
The state class declaration code is shown Below:
#include <iostream>
#include "Transition.h"
using namespace std;
class State: public Transition
{
protected:
StateContext* currentContext;
public:
State(StateContext* Context);
};
The this pointer is only valid inside a class. Your insertMoney function is not declared to be in a class. See http://www.learncpp.com/cpp-tutorial/87-the-hidden-this-pointer/.
In your definiton of insertMoney (in the code, not the class), you do not declare it to be a member of hasCredit. You need to use void hasCredit::insertMoney instead.
You probably want to attach insertMoney to a class. Try ClassName::insertMoney in your definition.
The error is telling you exactly why you're getting it.
The solution is to fix the definition of what you intend to be a member function, so that the compiler knows it is a member function. Like this:
// vv THIS WAS MISSING
void HasCredit::insertMoney(int money)
{
...
Your member declarations shown in the question are also in the wrong place. They need to be inside the class body, but outside the constructor. When overriding virtual member functions, you may want to show that to readers by using the virtual and override keywords. (Note, override only works if you have a new, C++11 compiler. For older compilers, use a comment /* override */ instead)
class HasCredit: public State
{
HasCredit (StateContext* Context) : State(Context) { }
// vv THIS....................CANNOT BE INSIDE HERE ^^
virtual void insertMoney(int) override;
...
};
You probably want some of your members to be public as well.
There are a few things wrong:
class definition:
#include <iostream>
#include "State.h"
#include "StateContext.h"
using namespace std;
class HasCredit: public State
{
HasCredit (StateContext* Context) : State(Context) {
}
void insertMoney(int);
void MakeSelectionCoating(int);
void MakeSelectionFilling(int);
void moneyRejected(void);
void addPopTarts(int);
void dispense(void);
};
Note that the methods should be declared outside of the constructor definition.
For the implemenation:
#include <iostream>
#include "HasCredit.h"
using namespace std;
void HasCredit::insertMoney(int money)
{
cout<<"You inserted: " << money;
money = money+this->currentContext->getStateParam(Credit);
this->currentContext->setStateParam(Credit,money);
cout<< "Total: "<<money<<endl;
this->currentContext->setState(Has_Credit);
}
The method must be qualified with the name of the class... otherwise it would be considered a definition of a function... and a function does not have a this

C++ Inheritance - Running Parent Method in Child Class

My parent class, Course, has the method addStudent(Student s). My child class, BetterCourse, inherits from Course. Every time I try to run BetterCourse.addStudent(s), I get the following error:
error: no matching function for call to
‘BetterCourse::addStudent(Student (&)())’ note: candidates are: void Course::addStudent(Student)
I understand it's telling me addStudent() hasn't been defined in BetterCourse and that it's recommending I use the one present in the parent class, Course. This has me confused as the whole idea around inheritance is not needing to redefine inherited functions and variables.
Course is as follows:
#include <iostream>
#include <string>
#include "Student.h"
using namespace std;
class Course
{
protected:
string id;
string name;
public:
Course();
Course(string id, string name);
void addStudent(Student s);
};
Course::Course()
{
//code
}
Course::Course(string id, string name)
{
//code
}
void Course::addStudent(Student s)
{
//code
}
BetterCourse:
#include <iostream>
#include <string>
#include "Course.h"
using namespace std;
class BetterCourse : public Course
{
public:
BetterCourse(string id, string name) : Course(id,name){};
};
From your error it seems that you for the first time get to the ugliest part of C++.
This:
Student s();
Is function declaration - not object definition. s type is Student (*)() so when you call:
BetterCourse bc;
bc.addStudent(s);
You get your error - you don't have method to add functions returning Student.
Define Student in the following ways:
Student s;
Student s {}; // new C++11 way
Student s = Student(); //
It sounds like you're actually calling the function 'addStudent' with an inappropriate argument. Could you show the code that is actually calling addStudent on the BetterCourse object? It sounds like you're using a reference to the student instead of the student object itself.
you can not call BetterCourse.addStudent(s) you should create an object
BetterCourse obj;
obj.addStudent(s);
should work
If you want to call BetterCourse::addStudent(s) than declare addStudent(s) as static method