Char to char* C++ - c++

I'm having an error with my constructor in my classes.
In my .cpp file I've got:
Player::Player()
{
m_name="Jane";
m_amt=100;
}
and in my .h file I've got:
// Default constructor, does nothing.
Player();
// Creates a Player. Player name and amount.
Player(const char &name, int amt);
I'm getting the error:
error: invalid conversion from ‘const char*’ to ‘char’ [-fpermissive]
m_name="Jane";
So I tried converting it to a *char but that still doesn't work. Can someone help please?

You can either take a pointer:
Player(const char* name, int amt) { ... }
and you could use std::string to store the name and use char* just to construct this string:
private:
std::string m_name;
public:
Player(const char* name, int amt) : m_name(name) { }
or just use std::string everywhere and pass by reference to avoid redundant copies being created:
private:
std::string m_name;
public:
Player(const std::string& name, int amt) : m_name(name) { }
Note that the last version is quite flexible and it's possible to also pass const char* to it, example:
#include <iostream>
#include <string>
class Player {
private:
std::string m_name;
public:
Player(const std::string& name) : m_name(name){}
void printName() { std::cout << m_name; }
};
int main() {
Player p("Liho");
p.printName();
}

Show your full class/code. Following compiles fine for me.
cpp file...
#include"player.h"
Player::Player()
{
m_name="Jane";
m_amt=100;
}
.h file...
class Player {
public:
// Default constructor, does nothing.
Player();
// Creates a Player. Player name and amount.
Player(const char *name, int amt);
private:
char* m_name;
int m_amt;
};

Related

No declaration matches in Codelite IDE

I have been looking in different threads with this error which is quite common but it feels like the IDE I am using messed with my workspace and I can't quite find the problem. I am setting up an extremely basic class called "Movie" that is specified below:
Movie.hpp :
#ifndef MOVIE_HPP
#define MOVIE_HPP
#include <iostream>
#include <string>
using std::string, std::cout,std::size_t;
class Movie
{
private:
std::string name;
std::string rating;
int watched_ctr;
public:
Movie(const string& name, const string& rating, int watched_ctr);
~Movie();
//getters
string get_name() const;
string get_rating() const;
int get_watched() const;
//setters
void set_name(string name);
void set_rating(string rating);
void set_watched(int watched_ctr);
};
#endif // MOVIE_HPP
Movie.cpp:
#include <iostream>
#include <string>
#include "Movie.hpp"
using std::string, std::cout,std::size_t,std::endl;
Movie::Movie(const string& name, const string& rating, int watched_ctr)
: name(name) , rating(rating) , watched_ctr(watched_ctr) {
}
Movie::~Movie()
{
cout << "Destructor for Movies class called /n";
}
//Getters
string Movie::get_name(){return name;}
string Movie::get_rating(){return rating;}
string Movie::get_watched(){return watched_ctr;}
//Setters
void Movie::set_name(std::string n){this -> name = n;}
void Movie::set_rating(std::string rating){this -> rating = rating;}
void Movie::set_watched(int ctr){this -> watched_ctr = ctr;}
The main.cpp I am trying only consists in creating one Movie object:
#include <iostream>
#include <string>
#include "Movie.hpp"
using std::string, std::cout,std::size_t,std::endl;
int main()
{
Movie StarTrek("Star Trek", "G", 20);
}
As you can see, I set all the attribute to private in order to exercise with the set/get methods but I keep stumbling upon the same error on each of them stating >"C:/Users/.../ProjectsAndTests/MoviesClass/Movie.cpp:18:8: error: no declaration matches 'std::__cxx11::string Movie::get_name()"
if you could give me a hint on what might cause this error I would greatly appreciate thank you!
I tried opening another workspace with classes implemented inside of them and the syntax I am using is very close from this test workspace I opened which compiled fine (no error regarding declaration match).
There are 2 problems with your code.
First while defining the member functions outside class you're not using the const. So to solve this problem we must use const when defining the member function outside the class.
Second, the member function Movie::get_watched() is declared with the return type of string but while defining that member function you're using the return type int. To solve this, change the return type while defining the member function to match the return type in the declaration.
//----------------------vvvvv--------->added const
string Movie::get_name()const
{
return name;
}
string Movie::get_rating()const
{
return rating;
}
vvv------------------------------>changed return type to int
int Movie::get_watched()const
{
return watched_ctr;
}
Working demo

No default constructor exists for class c++ [duplicate]

This question already has answers here:
Why does C++ allow us to surround the variable name in parentheses when declaring a variable?
(2 answers)
Closed 5 years ago.
Hello,
I'm trying to instantiate an anonymous object with a std::string variable 'name'. But intellisenen gives me error saying
E0291 no default constructor exists for class "Player" GoldGame e:\C++ Projects\Hello World\GoldGame\GoldGame.cpp 17
I have provided a constructor which can just take a std::string variable since other parameters are provided with default value.
Can you guys shed some light on this?
What confuses me even more is that when I change
Player(name);
to
Player a(name);
or to
Player("test");
then intellisense becomes totally fine with those.
GoldGame.cpp
#include "stdafx.h"
#include "Creature.h"
#include "Player.h"
#include <iostream>
#include <string>
int main()
{
std::cout << "Enter your name: ";
std::string name;
std::cin >> name;
Player(name);
return 0;
}
Creature.h
#pragma once
#include <string>
class Creature
{
public:
Creature(const std::string &name, const char symbol, const int health, const int damage, const int gold);
~Creature();
//getters
const std::string& getName() { return m_name; }
const char getSymbol() { return m_symbol; }
const int getHealth() { return m_health; }
const int getDamage() { return m_damage; }
const int getGold() { return m_gold; }
//health, gold and dead
void reduceHealth(const int healthMinus);
void addGold(const int gold);
bool isDead();
private:
std::string m_name;
char m_symbol;
int m_health;
int m_damage;
int m_gold;
};
Creature.cpp
#include "stdafx.h"
#include "Creature.h"
Creature::Creature(const std::string & name, const char symbol, const int health, const int damage, const int gold)
:m_name(name), m_symbol(symbol), m_health(health), m_damage(damage), m_gold(gold)
{
}
Creature::~Creature()
{
}
void Creature::reduceHealth(const int healthMinus)
{
m_health -= healthMinus;
}
void Creature::addGold(const int gold)
{
m_gold += gold;
}
bool Creature::isDead()
{
if (m_health>0)
{
return true;
}
else
{
return false;
}
}
Player.h
#pragma once
#include "Creature.h"
#include <string>
class Player :
public Creature
{
public:
Player(const std::string &name, const char symbol='#', const int health=10, const int damage=1, const int gold=0);
~Player();
const int getLevel() { return m_level; }
void levelUp();
bool hasWon();
private:
int m_level;
};
Player.cpp
#include "stdafx.h"
#include "Player.h"
Player::Player(const std::string & name, const char symbol, const int health, const int damage, const int gold)
:Creature(name,symbol,health,damage,gold)
{
}
Player::~Player()
{
}
void Player::levelUp()
{
++m_level;
}
bool Player::hasWon()
{
if (m_level>=20)
{
return true;
}
else
{
return false;
}
}
Player(name); does not do what you think it does. It declares a new variable name of type Player and calls a default constructor. If you want to instantiate an anonymous Player variable then you need to write
(Player(name));
// or
Player{name}; // list initialization since C++11

Trying to set up a class thru .h and .cpp files -- why do I get these errors?

I'm using g++ on Debian 8.2 Jessie.
I'm learning about classes in C++. I think I understand the basics, but not fully how to instantiate class objects with header files.
Here's Movie.h:
#ifndef MOVIE_H
#define MOVIE_H
#include <string>
#include <iostream>
class Movie
{
private:
std::string m_title;
int m_releaseYear;
std::string m_description;
public:
Movie(std::string &title, int releaseYear, std::string &description);
~Movie()
{
std::cout << "\nDestructor called\n";
}
void setMovieInfo(std::string &title, int releaseYear, std::string &description);
std::string getTitle();
int getReleaseYear();
std::string getDescription();
void printInfo();
};
#endif
Then there's Movie.cpp:
#include "Movie.h"
// Movie constructor
Movie::Movie(std::string &title, int releaseYear, std::string &description)
{
setMovieInfo(std::string &title, int releaseYear, std::string &description);
}
// Movie mem function
void Movie::setMovieInfo(const std::string &title, const int releaseYear, const std::string &description)
{
m_title= title;
m_releaseYear= releaseYear;
m_description= description;
}
std::string Movie::getTitle()
{
return m_title;
}
int Movie::getReleaseYear()
{
return m_releaseYear;
}
std::string Movie::getDescription()
{
return m_description;
}
void Movie::printInfo()
{
std::cout << "Title: " << m_title << '\n';
std::cout << "Year: " << m_releaseYear << '\n';
std::cout << "Description" << m_description << '\n';
}
And main.cpp:
#include "Movie.h"
int main(){
std::string title;
int releaseYear;
std::string description;
title= "Blade Runner";
releaseYear= 1982;
description= "Harrison Ford's character hunts a group of runaway four-year-olds.";
Movie bladeRunner(title, releaseYear, description);
bladeRunner.printInfo();
return 0;
}
I ran g++ -Wall Movie.cpp main.cpp -o main.sh && ./main.sh, but got this output:
Movie.cpp: In constructor ‘Movie::Movie(std::string&, int, std::string&)’:
Movie.cpp:6:27: error: expected primary-expression before ‘&’ token
setMovieInfo(std::string &title, int releaseYear, std::string &description);
^
Movie.cpp:6:35: error: expected primary-expression before ‘int’
setMovieInfo(std::string &title, int releaseYear, std::string &description);
^
Movie.cpp:6:64: error: expected primary-expression before ‘&’ token
setMovieInfo(std::string &title, int releaseYear, std::string &description);
^
Movie.cpp: At global scope:
Movie.cpp:10:6: error: prototype for ‘void Movie::setMovieInfo(const string&, int, const string&)’ does not match any in class ‘Movie’
void Movie::setMovieInfo(const std::string &title, const int releaseYear, const std::string &description)
^
In file included from Movie.cpp:1:0:
Movie.h:20:8: error: candidate is: void Movie::setMovieInfo(std::string&, int, std::string&)
void setMovieInfo(std::string &title, int releaseYear, std::string &description);
^
Reference parameters to functions can initially be a little confusing. While you define a function with
void foo(int& i){}
When you call the function, you do not need to pass a reference. So you would call
foo(x);
rather than
foo(&x);
It can initially be confusing. In your case, simply call
Movie bladeRunner(title, releaseYear, description);
Also, it's worth noting that in your code there is no reason to have the parameters to the constructor be reference parameters. It does reduce memory usage a little, but that really shouldn't be a concern when you're first trying to get your code working. So Movie(std::string title, int releaseYear, std::string description) would be fine.
The call to setMovieInfo in the constructor should simply be setMovieInfo(title, releaseYear, description);. As it was originally written it is one return type away from being a function declaration.
The signatures for the declaration and definition of Movie::setMovieInfo do not match, the const needs to be removed from the one, or added to the to the other.
Given the function signatures void fn(const int&) and void fn(int&), the compiler is able to differentiate them based on the const, they are not the same function signatures. So in the class definition you declare the setMovieInfo with a signature, when you define it in the cpp file, you give it another signature - this is not allowed, the signatures need to be the same.
The constructor has three parameters, reference to string, int and another reference to string. As the parameters for the string are references, you can either pass a pointer or the variable in the object instantiation.
For example, a reference can only be
int a;
int &b = a;
You have written something like
int &b = &a;
which is unacceptable.
You can either use two of the below while you instantiate the object
Movie bladeRunner(title, releaseYear, description);
or create a pointer for title and description and pass the pointer.
This is because only a pointer or a variable can be passed to a reference. Here, the constructor stores your parameters as reference to a reference for title and description. I see the same mistake in the function call of setMovieInfo inside constructor.
Also in your definition of constructor, you are calling setMovieInfo. You need not mention the types in the parameters of setMovieInfoas they are already declared in the constructor's parameters. There is also another problem. For the function declaration in Movie.h forsetMovieInfo you have not used any const. Please remove the const in the function definition in Movie.cpp.
Correct these errors and your program will run fine.
From all the suggestions, I've come up with this working code.
Movie.h:
#ifndef MOVIE_H
#define MOVIE_H
#include <string>
#include <iostream>
class Movie
{
private:
std::string m_title;
int m_releaseYear;
std::string m_description;
public:
Movie(std::string &title, int releaseYear, std::string &description);
~Movie()
{
std::cout << "\nDestructor called\n";
}
void setMovieInfo(std::string &title, int releaseYear, std::string &description);
std::string getTitle();
int getReleaseYear();
std::string getDescription();
void printInfo();
};
#endif
Movie.cpp:
#include "Movie.h"
// Movie constructor
Movie::Movie(std::string &title, int releaseYear, std::string &description)
{
setMovieInfo(title, releaseYear, description);
}
// Movie mem function
void Movie::setMovieInfo(std::string &title, int releaseYear, std::string &description)
{
m_title= title;
m_releaseYear= releaseYear;
m_description= description;
}
std::string Movie::getTitle()
{
return m_title;
}
int Movie::getReleaseYear()
{
return m_releaseYear;
}
std::string Movie::getDescription()
{
return m_description;
}
void Movie::printInfo()
{
std::cout << "Title: " << m_title << '\n';
std::cout << "Year: " << m_releaseYear << '\n';
std::cout << "Description: " << m_description << '\n';
}
main.cpp:
#include "Movie.h"
int main(){
std::string title;
int releaseYear;
std::string description;
title= "Blade Runner";
releaseYear= 1982;
description= "Harrison Ford's character hunts a group of runaway four-year-olds.";
Movie bladeRunner(title, releaseYear, description);
bladeRunner.printInfo();
return 0;
}

Error no member function declared in class when compiling

I am pretty new to c++ and have no idea why I am getting this error, except that I think it's to do with using the string type for getter methods.
The error message:
C:\Users\Robin Douglas\Desktop\week6>g++ -c Student.cpp
Student.cpp:15:31: error: no 'std::string Student::get_name()' member function d
eclared in class 'Student'
Student.cpp:20:43: error: no 'std::string Student::get_degree_programme()' membe
r function declared in class 'Student'
Student.cpp:25:32: error: no 'std::string Student::get_level()' member function
declared in class 'Student'
Student.hpp
#include <string>
class Student
{
public:
Student(std::string, std::string, std::string);
std::string get_name;
std::string get_degree_programme;
std::string get_level;
private:
std::string name;
std::string degree_programme;
std::string level;
};
Student.cpp
#include <string>
#include "Student.hpp"
Student::Student(std::string n, std::string d, std::string l)
{
name = n;
degree_programme = d;
level = l;
}
std::string Student::get_name()
{
return name;
}
std::string Student::get_degree_programme()
{
return degree_programme;
}
std::string Student::get_level()
{
return level;
}
The following code defines fields (variables) rather then methods.
public:
Student(std::string, std::string, std::string);
std::string get_name;
std::string get_degree_programme;
std::string get_level;
Then, when you implement it in the .cpp file the compiler complains that you try to implement a method that was not declared (since you declared get_name to be a variable).
std::string Student::get_name()
{
return name;
}
To fix, just change your code as below:
public:
Student(std::string, std::string, std::string);
std::string get_name();
std::string get_degree_programme();
std::string get_level();

No matching constructor for initialization of

I’ve seen similar questions on StackOverflow, but none of them seems to apply to me.
Here is my code:
Option.cpp
#include "Option.h"
Option::Option(string valueName, string description, OptionType type){
this->valueName = valueName;
this->description = description;
this->type = type;
};
Option.h
#include <iostream>
using namespace std;
enum OptionType { FLAG, REQUIRED, NORMAL };
class Option {
string valueName, description, value;
OptionType type;
public:
Option(string valueName, string description, OptionType type);
void setValue(string value) {
this->value = value;
};
string getValueName() {
return this->valueName;
};
string getDescription() {
return this->description;
};
OptionType getType() {
return this->type;
};
};
Options.cpp
#include "Options.h"
using namespace std;
Options::Options(int _argc, const char * _argv[]) : argv(_argv) {
this->argc = _argc;
}
Options::~Options() {
options.~unordered_map();
}
void Options::printHelp() {
for (auto &i : options) {
cout << i.first << '\t' << i.second.getDescription() << '\n';
}
}
void Options::addFlag(string flagName, string description) {
}
void Options::addOption(string optionName, string valueName, string description, OptionType type) {
Option option(valueName, description, type);
options[optionName]=option;
}
void Options::addOptionAlias(string aliasName, string optionName) {
}
Options.h
#include <iostream>
#include <unordered_map>
#include "Option.h"
using namespace std;
class Options {
unordered_map<string, Option> options;
int argc;
const char ** argv;
public:
Options(int argc, const char * argv[]);
~Options();
void parse();
void addOption(string optionName, string valueName, string description, OptionType type);
void addFlag(string flagName, string description);
void addOptionAlias(string aliasName, string optionName);
void getOption(string optionName);
void printHelp();
};
It's in options.cpp on the line Option option(valueName, description, type); that the error seems to stem from, but for the life of me, I can’t figure out why. As far as I can see, the constructor in Option takes the right types.
The problem is actually in the next line:
options[optionName]=option;
That first calls the operator[] in the map, that searchs for the given key and returns the associated value. If the key is not found, it insert a default initialized value connected to that key. Then this value is copy assigned with your option.
Do you see the problem? Your Option class does not have a default constructor, so it cannot be default initialized! Read carefully your error message, surely it is talking about the default constructor, not the one you are looking at.
You have several solutions. The easiest would be to write a default constructor for your class.
The alternative would be never to use operator[] in the map so that the default constructor is never needed. If that's what you want to do, to insert an item you write:
options.insert(std::make_pair(optionName, option));
Finally, if you are using C++11 (or later) and a compliant enough compiler, you can even build the object directly into the container: zero copy overhead and you don't even need the copy constructor!
options.emplace(std::piecewise_construct,
std::forward_as_tuple(optionName),
std::forward_as_tuple(valueName, description, type));
There's a mismatch between the declaration of the constructor in the header and the definition in the source file.
In header...
Option(string& valueName, string& description, OptionType& type);
In source file...
Option::Option(string valueName, string description, OptionType type){
Notice the parameters are defined as references (e.g., string&) in the header, but as objects (e.g., string) in the source.