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;
};
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 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){}
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 10 months ago.
Improve this question
Question
You have to create a class, named Student, representing the student's details, as mentioned above, and store the data of a student. Create setter and getter functions for each element; that is, the class should at least have following functions:
get_age, set_age
get_first_name, set_first_name
get_last_name, set_last_name
get_standard, set_standard
Also, you have to create another method to_string() which returns the string consisting of the above elements, separated by a comma(,). You can refer to stringstream for this.
code:
#include <iostream>
using namespace std;
class Student{
private:
int age;
string fname;
string lname;
int std;
public:
void set_age(int a){age=a;;}
void set_fname(string f){fname=f;} //fname= first name
void set_lname(string l){lname=l;} //lname= last name
void set_std(int s){std=s;}
void get_age(){
cout<<age<<endl;
}
void get_fname(){
cout<<fname<<endl;
}
void get_lname(){
cout<<lname<<endl;
}
void get_std(){
cout<<std<<endl;
}
void to_string(){
string fl=lname+", "+fname; //fl stand for first and last
cout<<fl;
}
};
int main() {
Student z;
int a,s;
string f,l;
cin>>a;
z.set_age(a);
cin>>f;
z.set_fname(f);
cin>>l;
z.set_lname(l);
cin>>s;
z.set_std(s);
get_age();
to_string();
get_std();
return 0;
}
output
Solution.cpp:52:11: error: ‘get_age’ was not declared in this scope
cout<<get_age();
^~~~~~~
Solution.cpp:52:11: note: suggested alternative: ‘getdate’
cout<<get_age();
^~~~~~~
getdate
Solution.cpp:53:15: error: no matching function for call to ‘to_string()’
to_string();
^
You create one Student instance, z, and call misc. setter member functions on that instance. When you then call the functions to print some of the values you've set, you forgot to tell the compiler which instance you want to print the values for. Since you only have one instance, z, add that before the member functions:
z.get_age();
z.to_string();
z.get_std();
Improvement suggestion: Functions that does not return a value but that prints the value would be better named print-something rather than get-something.
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 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 9 years ago.
Improve this question
Doing a programming homework assignment and I am having some trouble with pointers. I'm not too sure what the issue is.
I have looked around and found a few solved issues but I can't seem to figure out how to implement the fixes in my own code. (noob)
in my main I call:
MotherShip* m1 = new MotherShip(5, 6);
I am getting the error "cannot instantiate abstract class" with this.
MotherShip.h:
#include "SpaceShip.h"
class MotherShip : public SpaceShip
{
public:
int capacity;
MotherShip();
MotherShip(int x, int y, int cap);
MotherShip(const MotherShip& ms);
void print();
};
MotherShip.cpp:
#include "stdafx.h"
#include "MotherShip.h"
MotherShip::MotherShip()
{
}
MotherShip::MotherShip(int x, int y, int cap)
{
}
MotherShip::MotherShip(const MotherShip& ms)
{
}
void MotherShip::print()
{
}
Here is my full main (I don't think it's important here so I thought I'd just pastie it)
http://pastie.org/pastes/8429256/text
You're passing two arguments to your class constructor, however you have not defined a constructor that takes two arguments.
One solution would be:
MotherShip* m1 = new MotherShip(5, 6, 7 /* passing third argument */);
Another solution is defining a constructor to take two arguments:
MotherShip(int x, int y);
you must set the cap parameter as your constructor requires it.
There's no constructor that takes two ints!
Use the default value in your declaration
MotherShip(int x, int y, int cap = 123);
or, as an alternative, declare and define another constructor that takes two ints:
MotherShip(int x, int y);
Could be guessed without looking. abstract class in C++ is implemented by adding a pure virtual function.
You sure have a pure virtual function in your base class SpaceShip which you need to override in MotherShip. Or else MotherShip too becomes abstract and cannot be instantiated.
class SpaceShip
{
public:
virtual void DoSomething() = 0; //override this with some implementation in MotherShip
};