I have a class AdventureGame which has a constructor. When I try to make a new AdventureGame object, I receive the error "no matching function for call to 'AdventureGame::AdventureGame()'
Here is some of my class, the constructor, and main.
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
class AdventureGame
{
private:
public:
int playerPos;
int ogrePos;
int treasurePos;
string location;
AdventureGame(int ogre, int treasure)
{
playerPos = -1;
ogrePos = ogre;
treasurePos = treasure;
location = "";
};
.
.
. // other functions that I'm sure are irrelevant
.
.
int main()
{
AdventureGame game;
int numMoves = 0;
std::string move;
while (!game.isGameOver(game.playerPos))
{
game.printDescription(game.playerPos);
cout << "Which direction would you like to move? (forward, left, or right)" << endl;
cin >> move;
game.move(move);
numMoves++;
}
}
How do I create a new game?
Your constructor expects two parameter you need to pass them.
Like this for instance:
AdventureGame game(3,5);
You should either create an empty constructor:
AdventureGame()
{
playerPos = -1;
ogrePos = 0;
treasurePos = 0;
location = "";
};
or always create your class passing ogrePos and treasurePos values to it:
AdventureGame game(0,0);
Probably it makes sense to create both empty and parameterized constructor.
You are calling a default constructor without defining it. Just calling AdventureGame game; calls a constructor function AdventureGame() {}; which is not defined. In order to call AdventureGame(int ogre, int treasure) write AdventureGame game (arg1, arg2) in the main function.
If you are using C++11 I would suggest the best practice will be always create new object with this format AdventureGame game {}. Using this format, AdventureGame game {} calls Default Constructor and AdventureGame game {arg1, arg2 ...} calls some other corresponding constructor.
Note that AdventureGame game (); DOES NOT call default constructor!!
Enjoy coding!!
Defualt Constructor is missing
AdventureGame()
{
playerPos = -1;
ogrePos = 0;
treasurePos = 0;
location = "";
}
Related
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;
}
I have to set up an object and, after an user chose, i have to change some param into the object but not every each.
example:
{
class Champ
{
private:
int hp;
std::string class;
public:
Champ();
Champ(std::string chose);
};
Champ::Champ() {hp=10; class="";}
Champ::Champ(std::string chose) {class = chose;}
main()
{
Champ Test;
std::string chose;
getline(cin,chose);
Test(chose);
return 0;
}
this code give me an error.
i need hp equal for all "Champ" created but class can be changed.
The hp can't be "const" because this value may undergo changes...
how can i do this? :/
The comments in the code below should explain what is going on well enough...
#include <iostream>
#include <string>
class Champ {
int hp;
std::string job;
public:
Champ():
hp(10) { } // don't need to explicitly initialize `job` because the default constructor for string does what we want.
explicit Champ(const std::string& choose):
hp(10),
job(choose) { }
};
int main(int argc, const char * argv[]) {
using namespace std;
// this is most like how you had it with the compile error fixed.
{
Champ test; // this creates a Champ object using the default constructor
string choose;
getline(cin, choose);
test = Champ(choose); // this creates a new Champ object and assigns it to test... Throwing away the one that was created earlier.
}
// this is, imho, a better way to do it:
{
string choose;
getline(cin, choose);
auto test = Champ(choose); // declare the variable as late as possible, and after you have all the data for its construction. That way, you only make one of them.
}
return 0;
}
I am struggling knowing how to create a class. I want to create a "Player" class and all I want to do is pass in the name while I'll have the other variables start at 0 until they are updated when a game is run (later in the program)
Player::Player(string name_in)
{
name = name_in;
int numOfWins = 0;
int numOfLoses = 0;
int numOfDraws = 0;
int totalMatches = 0;
}
Right now there are lots of errors around numOfWins, numOfLoses, numOfDraws and totalMatches. What can I do to fix this?
Perhaps the error is in your int ... part of assignments, which essentially creates a new local variable in a constructor.
Try this version:
#include <string>
using namespace std;
class Player
{
string name;
int numOfWins;
int numOfLoses;
int numOfDraws;
int totalMatches;
public:
Player(string name_in)
{
name = name_in;
numOfWins = 0;
numOfLoses = 0;
numOfDraws = 0;
totalMatches = 0;
}
};
You should declare other instance variables in the class declaration, rather than declaring them as locals (which is completely useless).
// This part goes in the header
class Player {
string name;
int numOfWins;
int numOfLoses;
int numOfDraws;
int totalMatches;
public:
Player(string name_in);
};
Now in the constructor you could use initialization lists:
// This part goes into the CPP file
Player::Player(string name_in)
// Initialization list precedes the body of the constructor
: name(name_in), numOfWins(0), numOfLoses(0), numOfDraws(0), totalMatches(0) {
// In this case, the body of the constructor is empty;
// there are no local variable declarations here.
}
Kinda vague, but I'll take a crack at it. You Probably want:
class Player{
string name;
int numOfWins;
int numOfLosses;
int numOfDraws;
int totalMatches;
Player(string name_in)
};
Player::Player(string name_in){
name = name_in;
numOfWins = 0;
numOfLosses = 0;
numOfDraws = 0;
totalMatches = 0;
}
Haven't used C++ in a while, so this may be faulty.
The errors you get, at least from the snippet you posted are caused for you can't declare variables in constructor - you declare them in class body and initialize in constructor or using another function.
#include <string>
class Player {
public:
Player( std::string const& name_in) : name( name_in),
numOfWins(), numOfLoses(),
numOfDraws(), totalMatches()
{} // constructor
// will initialize variables
// numOfWins() means default
// initialization of an integer
private:
std::string name;
int numOfWins;
int numOfLoses;
int numOfDraws;
int totalMatches;
};
usage:
int main() {
Player( "player_one");
return 0;
}
i want to run the function Run in the main, but am not allowed to create object due to no default constructor. when i try to create the default constructor, i receive the message, 'Error"Game::Game int maxComponents)" provides no initialiser for:'
//Game.h
#pragma once
#include "GameComponent.h"
#include <time.h>
class Game
{
private:
int componentCount;
GameComponent** components;
const int TICKS_1000MS;
public:
Game(){} //this does not work either
Game(int maxComponents){} //this does not work as my default constructor
~Game();
void Add(GameComponent*);
void Run();
};
//Game.cpp
#pragma once
#include "StdAfx.h"
#include "Game.h"
#include <iostream>
#include<time.h>
using namespace std;
void Game::Add(GameComponent*)
{
components= new GameComponent*[componentCount];
}
void Game::Run()
{
time_t rawtime;
struct tm * timeinfo;
time ( &rawtime );
timeinfo = localtime ( &rawtime );
//cout << timeinfo->tm_hour<< ":" << timeinfo->tm_min << ":" << timeinfo->tm_sec << endl;
for(int n=0;n<componentCount;n++)
{
components[n]->Update(timeinfo);
}
}
Game::~Game()
{
}
//main.cpp
#include "stdafx.h"
#include <iostream>
#include "Game.h"
#include <time.h>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
Game obj1;
obj1.Run();
system("pause");
return 0;
}
So, how do i create a default constructor here? i've tried to use member initialising too, doesn't work. and copy constructor.
A default constructor is a constructor that takes no arguments. So, you should declare a constructor that looks something like this:
Game() { }
You can keep your other constructor - normal function overloading applies to constructors, so it will use your Game(int) constructor when you specify a single integer argument, and Game() when you specify no arguments.
However, in your case Game contains a const int member (TICKS_1000MS). Since it's const, it's expected to be initialized in the constructor. So you should do something like this:
Game() : TICKS_1000MS(123) { } // replace 123 with whatever the value should be
You need to do that for all constructors.
It's a little silly to have a non-static const member of a class which is always initialized to the same value (as opposed to a value passed in as an argument to the constructor). Consider making it an enum instead:
enum { TICKS_1000MS = 123 };
or, a static const member:
static const int TICKS_1000MS;
and initialize it in Game.cpp:
const int Game::TICKS_1000MS = 123;
As long as you have defined a constructor other than than the default one, the default constructor is not provided anymore so you have to define it manually:
public:
Game() {}
Game(int maxComponents){}
Now you have a default constructor and an overloaded constructor which takes 1 integer parameter.
You will need to create the default parameterless constructor. When you define a constructor you no longer get the default that would have been created behind the scenes.
Game(){}
The default constructor is the one that does not take any parameters, in your case Game(){}.
You do not seem to use the constructor parameter, but if you do, you will have to provide a default value.
Probably you can so something along these lines, you class Game needs to initialize const int in both the constructors:
class Game
{
private:
int componentCount;
GameComponent** components;
const int TICKS_1000MS;
public:
Game(): TICKS_1000MS(100)
{} //this does not work either
Game(int maxComponents): TICKS_1000MS(100)
{} //this does not work as my default constructor
~Game();
void Add(GameComponent*);
void Run();
};
As pointed out by others you need to intialize const data in ctor or initializer list.
I'm having trouble declaring and initializing a char array. It always displays random characters. I created a smaller bit of code to show what I'm trying in my larger program:
class test
{
private:
char name[40];
int x;
public:
test();
void display()
{
std::cout<<name<<std::endl;
std::cin>>x;
}
};
test::test()
{
char name [] = "Standard";
}
int main()
{ test *test1 = new test;
test1->display();
}
And sorry if my formatting is bad, I can barely figure out this website let alone how to fix my code :(
If there are no particular reasons to not use std::string, do use std::string.
But if you really need to initialize that character array member, then:
#include <assert.h>
#include <iostream>
#include <string.h>
using namespace std;
class test
{
private:
char name[40];
int x;
public:
test();
void display() const
{
std::cout<<name<<std::endl;
}
};
test::test()
{
static char const nameData[] = "Standard";
assert( strlen( nameData ) < sizeof( name ) );
strcpy( name, nameData );
}
int main()
{
test().display();
}
Your constructor is not setting the member variable name, it's declaring a local variable. Once the local variable goes out of scope at the end of the constructor, it disappears. Meanwhile the member variable still isn't initialized and is filled with random garbage.
If you're going to use old-fashioned character arrays you'll also need to use an old-fashioned function like strcpy to copy into the member variable. If all you want to do is set it to an empty string you can initialize it with name[0] = 0.
Since you are using C++, I suggest using strings instead of char arrays. Otherwise you'd need to employ strcpy (or friends).
Also, you forgot to delete the test1 instance.
#include <iostream>
#include <string>
class test
{
private:
std::string name;
int x;
public:
test();
void display()
{
std::cout<<name<<std::endl;
}
};
test::test()
{
name = "Standard";
}
int main()
{
test test1;
test1.display();
std::cin>>x;
}
Considering you tagged the question as C++, you should use std::string:
#include <string>
class test
{
private:
std::string name;
int x;
public:
test();
void display()
{
std::cout<<name<<std::endl;
std::cin>>x;
}
};
test::test() : name("Standard")
{
}
c++11 actually provides two ways of doing this. You can default the member on it's declaration line or you can use the constructor initialization list.
Example of declaration line initialization:
class test1 {
char name[40] = "Standard";
public:
void display() { cout << name << endl; }
};
Example of constructor initialization:
class test2 {
char name[40];
public:
test2() : name("Standard") {};
void display() { cout << name << endl; }
};
You can see a live example of both of these here: http://ideone.com/zC8We9
My personal preference is to use the declaration line initialization because:
Where no other variables must be constructed this allows the generated default constructor to be used
Where multiple constructors are required this allows the variable to be initialized in only one place rather than in all the constructor initialization lists
Having said all this, using a char[] may be considered damaging as the generated default assignment operator, and copy/move constructors won't work. This can be solved by:
Making the member const
Using a char* (this won't work if the member will hold anything but a literal string)
In the general case std::string should be preferred