Im completely new to C++ and im trying to make a very simple text based combat system, but I keep getting the error: "objPlayer was not declared in this scope".
All the code is written before the main() function:
#include <iostream>
using namespace std;
//DECLARE THE UNIT CLASS
class generalUnit {
public:
int health; //the amount of health the unit has
};
//DECLARE THE PLAYER THOUGH THE UNIT CLASS
void generatePlayer() {
generalUnit objPlayer;
int objPlayer.health = 100;
}
//DECLARE AND INITIALIZE ALL COMMANDS
//CHECK STATS
void comCheckStats() {
cout << objPlayer.health << endl;
}
You don't have to create a variable inside a class pointing to the object of that class you are using. It is already declared and is called this.
With operator -> you can then access member variables from this. Like so:
#include <iostream>
#include <string>
using namespace std;
class Player
{
public:
int health;
// this is constructor
Player(int health_at_start)
{
this->health = health_at_start;
}
void comCheckStats()
{
cout << this->health << '\n';
}
};
int main()
{
// create player with 100 health
Player p1(100);
p1.comCheckStats();
// create player with 200 health
Player p2(200);
p2.comCheckStats();
}
As you can see, I am using something called constructor to create new instance of Player. It is just function without return type, declared with the same name as the class. It initializes member variable starting data and you can pass some values to it too.
Related
I am just learning about classes in C++, and I am trying to create this Coin class that simulates a coin flip with a method called toss() that will return either 0 or 1 which represent heads or tails respectively.
#include <iostream>
#include <cstdlib>
using namespace std;
class Coin {
private:
public:
Coin();
int toss();
};
Coin::Coin();
int Coin::toss() {
int num;
num = rand() % 2;
return num;
}
int main() {
Coin C;
cout << C.toss() << endl;
}
I keep getting an error that says: error: declaration of 'Coin::Coin()' outside of class is not definition. I am assuming that I did not declare my constructor correctly, but I am not sure.
The problem is that you're trying to declare the constructor outside the class when you wrote Coin::Coin();.
To solve this replace Coin::Coin(); with Coin::Coin(){} as shown below:
class Coin {
private:
public:
Coin();
int toss();
};
//----------v--->semicolon removed from here
Coin::Coin() //this is a definition now
{
}
Below is code for a simple book list with a class to store book names and isbn numbers into an overloaded function using a vector. This program runs fine and I can test it by returning a specific name (or isbn) using an accessor function from my class.
Question: I tried calling (instantiating?) a constructor with parameters from my class but it would not work, so I commented it out. Yet I was still able to run the program without error. From my main below - //BookData bkDataObj(bookName, isbn);
From watching tutorials, I thought I always had to make an object for a specific constructor from a class that I needed to call? My program definitely still uses my overloaded constructor and function declaration BookData(string, int); without making an object for it in main first.
Thanks for any help or input on this matter.
Main
#include <iostream>
#include <string>
#include <vector>
#include "BookData.h"
using namespace std;
int main()
{
string bookName[] = { "Neuromancer", "The Expanse", "Do Androids Dream of Electric Sheep?", "DUNE" };
int isbn[] = { 345404475, 441569595, 316129089, 441172717 };
//BookData bkDataObj(bookName, isbn); //how did program run without instantiating object for class?
vector <BookData> bookDataArr;
int arrayLength = sizeof(bookName) / sizeof(string);
for (int i = 0; i < arrayLength; i++) {
bookDataArr.push_back(BookData(bookName[i], isbn[i]));
}
cout << "Book 4 is: " << bookDataArr[3].getBookNameCl(); //test if works
return 0;
}
BookData.h
#include <iostream>
#include <string>
using namespace std;
class BookData
{
public:
BookData();
BookData(string, int); //wasn't I supposed to make an object for this constructor in my main?
string getBookNameCl();
int getIsbnCl();
private:
string bookNameCl;
int isbnCl;
};
BookData.cpp
#include "BookData.h"
BookData::BookData() {
bookNameCl = " ";
isbnCl = 0;
}
BookData::BookData(string bookNameOL, int isbnOL) { //how did I use this function
bookNameCl = bookNameOL; //definition without an object in main?
isbnCl = isbnOL;
}
string BookData::getBookNameCl() { //can still return a book name
return bookNameCl;
}
int BookData::getIsbnCl() {
return isbnCl;
}
Very new to programming so forgive me for maybe not seeing something obvious.
Basically I just want to know why all three codes do compile, but the resulting executables CRASH in cases TWO and THREE
(I marked the differences with comments)
ONE - compiles
#include <iostream>
#include <string>
using namespace std;
string testrace = "dog"; //defining it only globally
class Attributes {
public:
Attributes (string race){
if (race == "human"){
intelligence = 10;}
else if (race == "dog"){
intelligence = 4;}
}
int intelligence;
};
class Dalmatian: public Attributes{
public:
// but NOT locally
Dalmatian (): Attributes{testrace} { //using it as an argument
cout << "do i even arrive here" << endl;
}
};
int main() {
Dalmatian bob;
cout << bob.intelligence << endl;
}
TWO - crashes
#include <iostream>
#include <string>
using namespace std;
class Attributes {
public:
Attributes (string race){
if (race == "human"){
intelligence = 10;}
else if (race == "dog"){
intelligence = 4;}
}
int intelligence;
};
class Dalmatian: public Attributes{
public:
string testrace = "dog"; //only defining it locally
Dalmatian (): Attributes{testrace} { //using it as argument
cout << "do i even arrive here" << endl;
}
};
int main() {
Dalmatian bob;
cout << bob.intelligence << endl;
}
THREE - crashes
#include <iostream>
#include <string>
using namespace std;
string testrace = "dog"; //defining it globally
class Attributes {
public:
Attributes (string race){
if (race == "human"){
intelligence = 10;}
else if (race == "dog"){
intelligence = 4;}
}
int intelligence;
};
class Dalmatian: public Attributes{
public:
string testrace = "dog"; // AND locally
Dalmatian (): Attributes{testrace} { //using it as argument
cout << "do i even arrive here" << endl;
}
};
int main() {
Dalmatian bob;
cout << bob.intelligence << endl;
}
What I am looking for, of course, is a working alternative to example TWO.
However I am also interested in an explanation why all of the three pieces of code will compile fine, but executables resulting from 2 and 3 will crash.
EDIT: I do know that examples ONE and THREE don't make sense, I used them for demonstrational purposes. (Also fixed my wording, compiler did fine, executable crashed);
EDIT2: I do, of course, realize that I could just replace "testrace" with ""dog"", but for easier transferability to other subclasses, I would prefer a solution that lets me use a variable argument for Attributes(), that I can vary depending on the subclass, that is invoking the main class.
First off when you have
...
string testrace = "dog";
Dalmatian (): Attributes{testrace}
...
testrace will hide the global testrace as class members supersede global variables when you are in class scope. This means both example two and three use the same variable, the class member variable.
The reason two and three crash because you are trying to use a variable that has no been constructed before. When you get to
Dalmatian (): Attributes{testrace}
testrace has not yet been constructed. Even though you have string testrace = "dog"; in the class body that initialization doesn't happen until after Attributes{testrace} is called. So Attributes (string race) gets a uninitialized string and using it is undefined behavior and also causes your crash.
The problem is that at the time that Attributes is constructed the testrace variable is yet uninitialized, and accessing it gives you undefined behavior.
You can simply fix this by writing
Dalmatian (): Attributes{"dog"} { //using it as argument
cout << "do i even arrive here" << endl;
}
See the working code here.
I want to get a specific object in a class in C++. I looked into multiple sites and it seems my question is unique. Okay here's my code.
In House.h
#include <string>
using namespace std;
class House
{
string Name;
int Health;
public:
House(string a, int h);
void GetHouseStats();
void DamageHouse(int d);
~House();
};
in House.cpp
#include "House.h"
#include <iostream>
House::House(string a, int h)
{
Name = a;
Health = h;
}
void House::DamageHouse(int d) {
Health -= d;
cout << "Your " << Name << " has " << Health << " left."<<endl;
}
void House::GetHouseStats() {
cout << Name<<endl;
cout << Health;
}
House::~House()
{
}
in Source.cpp
#include <iostream>
#include "House.h"
using namespace std;
int main()
{
House Kubo("Bahay Kubo", 2);
Kubo.DamageHouse(1);
}
I have House Kubo as my first object. I would like to save the person's houses into a file but my problem is How can I pass the object's name into the function so that save its data into a file? I can manually place the Kubo and do so as
PlayerHouse = Kubo.Name;
But what if I don't know which house I should save? Like instead of typing down
PlayerHouse = Apartment.Name;//2nd house
PlayerHouse = Modern.Name;//3rd house
Can I use an function argument to place the object's name into PlayerHouse? Like this
void SetHouseName(type object){
PlayerHouse = object.Name;
}
Few ways in which this can be done .. is keeping all created object in a container and then access access the container to get the object in and pass it a function which will write it to a file .
Also if you do not want to maintain the container what you have mentioned about using the function will also work fine
Of course, but if you are going to save the Name of the house anyway, why don't you just ask for a std::string in the first place and then pass the Name to that function?
void SetHouseName(std::string name)
{
PlayerHouse = name;
}
If this is outside your House class you need to create a method to expose the Name member of House though, or just make it public.
To answer your initial question, just as how you would pass built-in types, you can do the same for your House type :
void SetHouseName(House house)
{
PlayerHouse = house.Name;
}
My problem is in the following C++ code. On the line with the 'cout' I get the error:
"'number' was not declared in this scope".
.h
using namespace std;
class a{
int number();
};
.cpp
using namespace std;
#include <iostream>
#include "header.h"
int main(){
cout << "Your number is: " << number() << endl;
return 0;
}
number(){
int x = 1;
return x;
}
Note: I'm aware this isn't the cleanest code. I just wanted to get the function working and refresh my memory on how to use headers.
For minimal fix, three basic changes are necessary.
Proper implementation of the number() method
int a::number() {
int x = 1;
return x;
}
Proper invocation of the number() method
a aObject;
cout << "Your number is: " << aObject.number() << endl;
There are many other enhancements possible though.
Addition, as pointed out by #CPlusPlus, usable scope of number() method, for example declaring it public
class a{
public:
int number();
};
Try this in your cpp file
using namespace std;
#include <iostream>
#include "header.h"
void a::number()
{
int x = 1;
return x;
}
int main()
{
cout << "Your number is: " << a().number() << endl;
return 0;
}
As for your header file replace class with a struct. The reason you are getting this error is because the compiler cant find the variable number. It is actually a method of a class.The reason you are replacing the class with a struct is because by default everything in a struct is public. So your header file called header.h should look like this
using namespace std;
struct a
{
int number();
};
There are three issues with your code.
The definition of the function number().
As you declared, it is a member function of the class "a". In your .cpp, the class name should be used as a prefix to the function. I mean,
a::number(){
int x = 1;
return x;
}
As the function is a member of the class "a", there are only two ways of accessing it,
If the function is a static function in the class, you can access it with :: operator. Like a::number().
If the function is not a static function, that is true in your case, you should instantiate the object out of the class "a" and they use "." operator with the reference. I mean,
a obj;
obj.number().
Your function number() is declared in private scope. You may recall that by default the scope is a class is private unless you specify public or protected. So the private function number() cannot be used outside the declared class unless there is a friend to it.
Below the code that I fixed,
.h
using namespace std;
class a{
public:
int number();
};
.cpp
using namespace std;
#include <iostream>
#include "header.h"
a::number(){
int x = 1;
return x;
}
int main(){
a obj;
cout << "Your number is: " << obj.number() << endl;
return 0;
}