Is this a constructor? - c++

say you have a class coded like this:
class Monster
{
public:
Monster(std::string& name, int hp, int acc, int xpReward
int armor, const std::string& weaponName,
int Lowdamage, int highdamage);
//insert methods
private:
//data types
};
what is the Monster(.... line do, create objects for the monster class? Is this a constructor? Really want to know everything this thing does

It's the declaration of a parameterized constructor. Right now, it's just the declaration, it does nothing, you did not post the code that belongs to it.

Related

C++ class templates: different data members and member functions for different typenames

I have two classes that intend to function the same but with different data members, as such:
class Character
{
protected:
string job;
int MAX_HP;
int HP;
int STR;
int DEX;
int INT;
public:
Character();
Character(string job,
int max_hp,
int str=0, int dex=0, int inte=0);
string get_name();
// get func and set func
int get_MAX_HP();
void add_MAX_HP(int MAX_HP);
int get_HP();
void add_HP(int HP);
int get_STR();
void add_STR(int STR);
int get_DEX();
void add_DEX(int DEX);
int get_INT();
void add_INT(int INT);
}
class Monster
{
protected:
string name;
int MAX_HP;
int HP;
int ATK;
int DEF;
public:
Monster(string name, int MAX_HP, int Shield, int Barrier, int ATK, int DEF);
string get_name();
int get_MAX_HP();
void add_MAX_HP(int MAX_HP);
int get_HP();
void add_HP(int HP);
int get_ATK();
void add_ATK(int ATK);
int get_DEF();
void add_DEF(int DEF);
}
These are all the difference between the two classes I have designed so far. As I am writing the other functionalities I start to realize that they work essentially the same despite the different data members, along with their getter and setter. I feel like making the two class declarations code into one. I think I can write a virtual base class for sure, that contains the union of all data members and member functions, and only initialize some members for Character or Monster. But can I achieve it with template? With template Character and Monster are instantiation of one template, but I am uncertain whether can template initialize different members in response to different typename...
Edit:
Allow me to be more specific. The Character and Monster are designed to fight. It also allows the Character and Character, Monster and Monster to fight. With two classes, there will be four member function in total to design:
class Character{
void Fight(Character hero, Monster enemy);
void Fight(Character hero, Character enemy);
}
class Monster{
void Fight(Monster mon, Character enemy);
void Fight(Monster mon, Monster enemy);
}
I want to make the Fight() function spread among two classes into one block to save code, as they all share using ATK/STR/DEX/INT to deduct HP of other object, DEF deducted for Monster. In finishing writing the function, I suspect a lot of copy & paste would be done, and code is already lengthy for getter and setter with similar functionalities, for each data member. I noticed a partial specialization for template. But it would be the same to write two separate code blocks for Character and Monster. Is it my class design that impedes merging homogeneous codes, or is it inevitable for C++, to write class with slight difference?

C++ Declaring an inherited constructor?

I'm having difficulties in defining a constructor for a class that inherits the properties of another class
class Transportation {
public:
int ID;
string company;
string vehicleOperator;
Transportation(int,string,string) {
}
};
class SeaTransport: public Transportation {
public:
int portNumber;
SeaTransport(int)::Transportation(int,string,string) {
}
};
I'm having issues with line 18 (SeaTransport(int)::Transportation(int,string,string)).
The error I receive occurs at the pont where I declare Transportation.
As seen in the code, a class Transportation is the body class and class SeaTransport inherits the properies of Transportation.
Transportation::Transportation(int, std::string, std::string)
+2 overloads
type name is not allowed
This error occurs at the int
typedef std::__cxx11::basic_string std::string
type name is not allowed
and this final error occurs at both string variables.
It seems you mix together scoping and a constructor initializer list.
The double-colon operator :: is for scope, while a constructor followed by a single colon and a list of initializations is an initializer list.
You must declare the SeaTransport constructor to take all the arguments, including those for the parent class (assuming you want to pass them on to the base constructor):
SeaTransport(int port, int id, string company, string operator);
Then in the definition (implementation) of the constructor you "call" the parent constructor in the constructor initializer list:
SeaTransport(int port, int id, string company, string oper)
: Transport(id, company, oper), // "Call" the parent class constructor
portNumber(port) // Initialize the own members
{
}
As Mr Some Programmer Dude said, you've a Scope problem in your code,
I will try to answer for your second question which is, how to add featured variables on your constructor.
Same as what you did for the port attribute.
You can define before all your Attribute which is boatNumber as int boadNumber = 0 then, you'll overload your
constructor with boatNumber(num) after the initializer operator and int num before the initializer operator.
class Transportation {
public:
int ID;
string company;
string vehicleOperator;
Transportation(int,string,string) {
}
~Transportation(){}
};
class SeaTransport: public Transportation {
public:
int portNumber;
int boatNumber;
SeaTransport(int num, int port, int id, string company, string oper)
:Transportation(id, company, oper), boatNumber(num),portNumber(port) {}
~SeaTransport(){}
};
But, if you want to get things more specific, you can create another class which is derived from SeaTransport
And then you'll define the number of your boat and more other details, if you want.
I'll draw you an instance of it :
class Boat: public SeaTransport {
public:
int boatNumber;
Boat(int bNum,int num, int port, int id, string company, string oper):
SeaTransport( num, port, id, company, oper),boatNumber(bNum){}
~Boat(){}
};

how to create a class from an identifier?

the title might be a bit misleading, but I want to give some instance of a class an instance of a different class through polymorphism. I think that may have been even more misleading so I'll give an example;
Say I have a class called Spell, that is a parent class to the class Firebolt. I want another class, say Character, to be able to have the spell, 'Firebolt', in an its memory without ever having to #include the files for 'Firebolt'.
Now, I can think of a way that prior games have done this before. By giving each spell (or whatever else specific class type) a static const string ID or name and in spell having some function that can access this ID/name and return a new Firebolt() if they are the same.
This sounds pretty good actually, the problem I'm having is I don't know how to code this. I'm not sure how I can access these ID's from the parent class, and I'm not sure how to make a virtual function that will actually return the correct Spell. Any help would be amazing. I'll also provide the actual class code I'm working with here in case it might help you guys to answer, or someone with a similar problem to solve it.
The parent class;
class Art {
std::string name;
int EPCost;
int castTime;
int AoESize;
public:
Art(std::string n, int cp, int ct, int as):name(n), EPCost(cp), castTime(ct), AoESize(as) {}
virtual ~Art() {}
static Art* findArt(std::string ID);
int getAoESize() {return AoESize;}
std::string getName() {return name;}
int getEPCost() {return EPCost;}
virtual int getBaseDamage() = 0;
};
The subclass;
class FireBolt:public Art {
static const std::string name;
static const int EPCost;
static const int castTime;
static const int AoESize;
static const std::string ID;
public:
FireBolt():Art(name, EPCost, castTime, AoESize) {}
~FireBolt() {}
int getBaseDamage();
};
All you need to do is make your FireBolt::ID public.
class FireBolt:public Art {
public:
static const std::string ID;
...
};
Art* Art::findArt(const std::string& ID)
{
if (ID == FireBolt::ID)
return new FireBolt(...);
...
}

How to pass "&player" object into another inherited class constructor ("score")?

I am new to C++ and I am creating a small program to understand more about inheritance in programming languages.
From what I gather, inheritance is when you have the authority and permission to obtain all member functions and values of the parent/base class. An analogy in real life would be inheriting some of my father's physical properties like eye colour etc (although I wish I could inherit his business mind...)
Anyways, one thing I am trying to do is to try and pass an already initialized object into an inherited class constructor.
This is my code so far:
#include <string>
#include <iostream>
using namespace std;
class player{
private:
string name;
int level;
public:
player(const string &n, const int &l) : name(n), level(l){};
string getName() const {return name;}
int getLevel() const {return level;}
};
class score: public player{
private:
int scores;
public:
score(const int &s, const string &n, const int &l) : player(n, l), scores(s){};
void setScore(int newScores){scores = newScores;}
int getScore() const {return scores;}
};
int main(){
player steve("steve", 69);
cout << steve.getName() << endl;
cout << steve.getLevel() << endl;
}
Basically, I want to pass the object that I have intialised in my main() program function steve by reference into a constructor in the score class. However, I don't know how to do this? Would it be something like score(const player &p, const int &s) : player(&p), scores(s)?? I get how to pass like member values, but I am interested in passing in objects themselves?
Would mean a lot if someone could assist me here, as I really like programming especially C++
You can't extend an object of a base class (player) to an object of a child class (score) because this would require to allocate more memory space directly after the original object to store the additional elements of the child class.
In your example, you can define this constructor to copy values from the player object for a new score object:
score(const player &p, const int &s) : player(p.n, p.l), scores(s){};
If you just want to link the player object, then the score class must include a pointer to this object.

C++ Class Inheritance Order

This is similar to other questions I'm sure, I read through. I am trying to write a move class. I need a Player class and an Item class that inherits the move class, or vice versa. That is what I am having difficulty with. I can't wrap my head around, or get to work, a way that the base class is not "Move." I'm lost here...
class Player {
protected:
int x;
int y;
int str;
int speed;
int level;
int exp;
public:
Player(int _str, int _speed, int _level, int _exp) { x=0;y=0;str=_str;speed=_speed;level=_level;exp=_exp; }
int GetX() {return x;}
int GetY() {return y;}
int GetStr() {return str;}
int GetSpeed() {return speed;}
int GetLevel() {return level;}
int GetExp() {return exp;}
};
class Move : public Player {
public:
void TryMove(int n) { x += n; }
};
int main(int argc, char *argv[])
{
Player You(101, 5, 3, 43625);
//You.TryMove(5); how?
}
TryMove(5) fails. If I do it the other way, then they type is then Move (?) and that doesn't sound right at all...
The way that I would recommend thinking of it is the Is A or Has A idiom. So... Is the Player a Move? Probably not, Is the Move A Player? also probably not. Then lets try the Has A. Does The Move Have a Player or Does the Player Have A move? I would Say that the Player Has a Move Personally. This would mean not using inheritance but rather having the player contain an instance of the Move class. So...
class Player{
public:
Move myMove;//where move is defined already as whatever you need it to be.
};
//then your main
int main(int argc, const char** argv){
//...other setup here
Player p;
p.myMove.TryMove(10);
//whatever else...
}
This is how i might approach your design. As far as the error... In the code above you had Move inherit from Player but you created a Player and expected it to have the functionality of Move but it would have no way of having that functionality based on the inheritance you set up in the example code.
Let me know if you need any clarification of what I have said or anything else. Good Luck
EDIT:
Based on your comment I would suggest that you use a wrapper function that will get the value that you need.
class Player{
public:
void TryMove(int i);
private:
Move myMove;
int x;//the value you will be getting from Move::tryMove
};
void Player::TryMove(int i){
this->x = myMove.tryMove(i);//store the value of the function call
//the function obviously won't be a void function in this case
}
There are other ways you could do this but this way is simple. If you are set on using inheritance to solve your problem I would have Player inherit from Move, But I still stand by my original answer I just wanted to help explain further.
First of all, public inheritance means IS-A relationship. So Move IS-A Player does not make any sense. Your design is wrong.
About your error, this is just silly. You are creating a Player object You and calling method of Move on it. To use methods of class Move, you have to create object of Move(or any publicly derived class).
class Move : public Player {
public:
//either create a ctor that will pass params to parent ctor, or create an empty ctro in parent class
Move(int _str, int _speed, int _level, int _exp):Player(_str,_speed,_level,_exp){}
void TryMove(int n) { x += n; }
};
int main(int argc, char *argv[]){
Move You(101, 5, 3, 43625);
You.TryMove(5);
}
I would design it as following:
class Movable{
public:
virtual bool TryMove()=0;
};
class Player: public Movable {
public:
bool TryMove() override{
//implementation code
}
//other members
};
int main(){
Movable* player = new Player(101, 5, 3, 43625);
player->TryMove();
delete player;
}