Declaring a Class C++ - c++

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;
}

Related

How to initialize a structure variable to default values?

I am learning about structures now and I am trying to create default values for each variable of that structure type. My testing code is as follows:
#include<iostream>
using namespace std;
int main (void){
// DECLARING THE STRUCTURE
struct str_client{
char name[20] = "\0";
int age = 0;
double money = 0.00;
};
// DECLARING A VARIABLE OF THAT STRUCTURE TYPE (IN THIS CASE, AN ARRAY).
str_client client[3];
return (0);}
Is this initialization the correct way to do it?
Use constructor.
Since class and struct are similar.
struct str_client{
string name;
int age;
double money;
str_client()
{
name = "";
age = 0;
money = 0.0;
}
};
Edit
Using Member Initializer list will improve performance
struct str_client{
string name;
int age;
double money;
str_client()
: name(""), age(0), money(0.0)
{
}
};

c++ 2 Constructor 1 Object, How to?

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;
}

error "extra qualification ‘student::’ on member ‘student’ [-fpermissive] "

I am getting an error extra qualification ‘student::’ on member ‘student’ [-fpermissive].
And also why name::name such syntax is used in constructor?
#include<iostream>
#include<string.h>
using namespace std;
class student
{
private:
int id;
char name[30];
public:
/* void read()
{
cout<<"enter id"<<endl;
cin>>id;
cout<<"enter name"<<endl;
cin>>name;
}*/
void show()
{
cout<<id<<name<<endl;
}
student::student()
{
id=0;
strcpy(name,"undefine");
}
};
main()
{
student s1;
// s1.read();
cout<<"showing data of s1"<<endl;
s1.show();
// s2.read();
//cout<<"showing data of s2"<<endl;
//s2.show();
}
In-class definitions of member function(s)/constructor(s)/destructor don't require qualification such as student::.
So this code,
student::student()
{
id=0;
strcpy(name,"undefine");
}
should be this:
student()
{
id=0;
strcpy(name,"undefine");
}
The qualification student:: is required only if you define the member functions outside the class, usually in .cpp file.
It would be correct if definition of constructor would appear outside of class definition.
Similar code:
Change from:
class Solution {
public:
static int Solution::curr_h; // ----------------- ISSUE: "Solution::" is extra
static int Solution::curr_m; // ----------------- ISSUE: "Solution::" is extra
};
int Solution::curr_h = 0;
int Solution::curr_m = 0;
to:
class Solution {
public:
static int curr_h; // ----------------- FIX: remove "Solution::"
static int curr_m; // ----------------- FIX: remove "Solution::"
};
int Solution::curr_h = 0; // <------ good here - "Solution::" is required
int Solution::curr_m = 0; // <------ good here - "Solution::" is required
This happens because copy pasting statics require initialization outside of class, but also requires all the declaration (int) too.
Though it is correct, wish there is a easier/ better way to do the same.

How can I initialize char arrays in a constructor?

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

C++ class with static pointer

I don't understand pointers and references very well yet, but I have a class with static methods and variables that will be referenced from main and other classes. I have a variable defined in main() that I want to pass to a variable in this class with static functions. I want those functions to change the value of the variable that is seen in the main() scope.
This is an example of what I am trying to do, but I get compiler errors...
class foo
{
public:
static int *myPtr;
bool somfunction() {
*myPtr = 1;
return true;
}
};
int main()
{
int flag = 0;
foo::myPtr = &flag;
return 0;
}
Provide the definition of the static variable outside the class as:
//foo.h
class foo
{
public:
static int *myPtr; //its just a declaration, not a definition!
bool somfunction() {
*myPtr = 1;
//where is return statement?
}
}; //<------------- you also forgot the semicolon
/////////////////////////////////////////////////////////////////
//foo.cpp
#include "foo.h" //must include this!
int *foo::myPtr; //its a definition
Beside that, you also forgot the semicolon as indicated in the comment above, and somefunction needs to return a bool value.
#include <iostream>
using namespace std;
class foo
{
public:
static int *myPtr;
bool somfunction() {
*myPtr = 1;
return true;
}
};
//////////////////////////////////////////////////
int* foo::myPtr=new int(5); //You forgot to initialize a static data member
//////////////////////////////////////////////////
int main()
{
int flag = 0;
foo::myPtr = &flag;
return 0;
}