Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 months ago.
Improve this question
I am very new to C++ and I am trying to initialize an object called GameObject, in a class called Room, which holds a gameObjects array. The constructor of the GameObject class takes pointers as the parameters to initialize the fields. But I keep getting the error saying that there is "No matching constructor for initialization of GameObject. Could someone tell me what is my mistake here?
Sorry if this question is formatted badly, I am not used to asking C++ questions with multiple header files and source files. But please also correct me on this.
GameObject
GameObject::GameObject(string* _name, string* _description, char* _keyWord):
name(_name), description(_description), keyWord(_keyWord){
}
Room
//error!, "No matching constructor for initialization..."
gameObjects[0] = new GameObject("knife", "a knife", 'k');
gameObjects[1] = new GameObject("sword", "a sword", 's');
};
Well, you in the GameObject constuctor:
GameObject::GameObject(string* _name, string* _description, char* _keyWord):
name(_name), description(_description), keyWord(_keyWord){}
You are accepting the two strings and a char by pointer. So maybe you meant to accept them by reference instead like this:
GameObject::GameObject(string& _name, string& _description, char _keyWord):
name(_name), description(_description), keyWord(_keyWord){}
Which works fine.
For instance take this program:
#include<iostream>
#include<string>
struct my_obj
{
my_obj(std::string s, std::string s_, char c)
: s__(s), s___(s_), char_(c) {}
std::string s__{};
std::string s___{};
char char_{};
};
struct my_obj_2
{
my_obj(std::string* s, std::string* s_, char* c)
: s__(s), s___(s_), char_(c) {}
std::string s__{};
std::string s___{};
char char_{};
};
int main()
{
my_obj my_obj_1("Hello", "Goodbye", 'C'); // works fine
my_obj_2 m_my_obj_2("Hello", "Goodbye", 'c'); // doesn't work fine
}
(1): This works fine because it finds a matching constructor:
std::string -> std::string
(2): Whereas this doesnt work fine because it is this conversion:
std::string -> std::string*
So in conclusion just remove the pointers on the constructor and if you wanted to you could pass then by & or const & like this
GameObject::GameObject(string& _name, string& _description, char _keyWord):
name(_name), description(_description), keyWord(_keyWord){}
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I dont exactly get the use of a constructor
For example:
class car
{
public:
string name;
long int price;
int mileage
bool ownedByPlayer;
};
Here, why will I use a constructor like this,
class car
{
public:
string name;
long int price;
int mileage
bool ownedByPlayer;
car()
{
ownedByPlayer = false;
}
};
if I can simply define the variable ownedByPlayer where I have declared it. Like: bool ownedByPlayer = false; ?
In your case there is no need to write the constructor. Actually it is recommended to not write a constructor that does nothing but initialize members with default values. Though the correct way would be to use the member initializer list:
car() : ownedByPlayer(false) {}
And since C++11 you can use a default member initializer instead:
class car {
// ...
bool ownedByPlayer = false;
// ...
};
Sometimes constructors actually need to do something. Consider a car registers itself somewhere after being constructed, then your class could look like this:
class car
{
public:
string name;
long int price;
int mileage;
car(string name,long int price, int mileage) : name(name),price(price),mileage(mileage) {
CarRegistrationFacility::register_car(*this);
}
};
Actually I found it difficult to make up an example for a constructor that does more than initializing members, because thats what constructors do. However, when your constructor does more than that, then that "more" happens in the body of the constructor.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
Longtime java programmer here, recently switched to C++ for the first time.
I am trying to have several constructors for a Person class. I have defined Person as follows:
class Person {
private:
//stuff
public:
Person(std::string firstName, std::string lastName, int age);
Person();//I want to define a constructor with no parameters, but NOT a default constructor!
};
My implementation:
#include "Person.h"
Person::Person(std::string firstName, std::string lastName, int age)
: firstName(firstName), lastName(lastName), age(age)
{
}
Person::Person()//no errors here
: firstName("default first"), lastName("default last"), age(0)
{
}
Finally, my main function:
int main() {
Person p1 = Person("Chuck", "Norris", 55)//Variable constructor
Person p2 = Person();//SHOULD invoke no-args constructor
return 0;
}
However, when I attempt to instantiate p2 using the no args constructor, I get the following error:
Expected a ';', which in this context makes no sense. I tried Person p2;, same issue.
How does one call a no-args constructor in C++ with user-defined default values?
You are missing a ; after p1!
int main() {
Person p1 = Person("Chuck", "Norris", 55) <-HERE
Person p2 = Person();//SHOULD invoke no-args constructor
return 0;
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
So I'm trying to write a little personal Planner App, and want store information in a class Tasks,
nothing to fancy yet but strcpy does not recognize the string c_task;
compiler say c:tastk is std:string Tasks::c_task so I understand that it is not the right argument for strcpy. So the question is how to make strcpy accept that string ?
class Tasks {
public:
string c_task = "";
int date;
int category;
int priority;
void newTask(string n_task);
};
void Tasks::newTask(string n_task)
{
strcpy_s(c_task, n_task);
}
Use std::string related functions. strcpy_s acts upon char * not on std::string.
class Tasks {
public:
std::string c_task = "";
int date;
int category;
int priority;
void newTask(std::string n_task);
};
void Tasks::newTask(std::string n_task)
{
c_task = std::move(n_task);
}
Strcpy is a standard library function for C language.You should use copy constructor of string.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I have a couple of questions I wanted to check with SO for my Data Structures in C++ course. They deal with the following class and multidimensional array:
class Order
{
public:
Order();
void addItem(string name, double price);
private:
static const int MAX_ITEMS = 10;
string itemNames[MAX_ITEMS];
int numItems; // # of items actually stored
double totalPrice;
};
const int TABLES = 10;
const int SEATS = 4;
Order diningRoom[TABLES][SEATS];
Q1: How many copies of MAX_ITEMS does the array diningRoom contain?
This is 40 right? There is one copy for each element in the array, 10*4.
Q2: Member function addItem should have been instead declared how?
A.) void addItem(const string &name, double price);
B.) void addItem(string &name, double price);
C.) void addItem(string name, double price) const;
D.) void addItem(string name[], double price);
A? Pass by const reference? This one I'm not too sure of.
No. There is one instance of MAX_ITEMS since it is a static member.
Yes. Const reference is the way to go.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 8 years ago.
Improve this question
Okay, so this is my first question on this site, and I'm fairly new to C++. I am trying to create a class of functions that puts the members of various campus clubs into their respective clubs. I was given this class skeleton to follow, but I'm not sure how to define the three constructors, especially how to use the variables that are inside of the parameters. You can pretty much ignore all of the public functions except the constructors. Any ideas?
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Club
{
public:
Club();
Club(Club &c);
Club(string cname);
void addMember(string name);
void removeMember(string name);
const string getClubName();
void loadClub();
const bool isMember(string name);
const string getAllMembers();
friend Club mergeClubs(Club& c1, Club& c2);
~Club();
private:
string *members;
int numMembers;
string clubName;
};
You have three constructors: the default Club(), the copy constructor Club(Club &c) and a third one Club(string cname).
For the default, you're going to have to decide what all the default values for your private members are.
For the copy constructor, all you need to do is copy everything from &c into your own record. So for instance you can do:
numMembers = c.numMembers ;
For the third one, you have to decide what cname is and what you should do with it.
For the copy constructor, you do have one tricky decision to make. What does it mean to copy string * members; You might think you could just say members= c.members ; but then if the original Club gets resized, the copy will be pointing to invalid memory.
Instead of using an array of strings, just use a vector, then you don't need the "numMembers" either.
class Club
{
public:
...
void addMember(string name) { members.push_back(name); }
void removeMemeber(string name) { members.erase(std::remove(members.begin(), members.end(), name), members.end()); }
...
private:
vector<string> members;
string clubName;
};