[C++]Constructor doesn't detect components [duplicate] - c++

This question already has an answer here:
C++ constructor definition differences in the code given below [closed]
(1 answer)
Closed 6 years ago.
I'm beginner in OOP and I have problem with definition of constructor.
headfile.h:
#ifndef RACHUNEK_H_INCLUDED
#define RACHUNEK_H_INCLUDED
#include <string>
class Rachunek
{
std::string surname;
std::string nr_account;
double balance;
public:
Rachunek();
Rachunek(std::string & name,std::string & nr,double s = 0.0);
~Rachunek(){};
void show();
void give(const double m);
void get(const double m);
};
#endif // RACHUNEK_H_INCLUDED
file .cpp:
#include <iostream>
#include <string>
#include "rachunek.h"
using namespace std;
Rachunek::Rachunek() //default
{
surname = "not specified";
nr_account = "0000-0000-0000-0000";
balance = 0.0;
}
Rachunek::Rachunek(string & name, string & nr, double s = 0.0) //mysecond
{
surname = name;
nr_account = nr;
balance = s;
}
the problem is the definition of a constructor. I don't know what is wrong...

the problem is the definition of a constructor. I don't know what is wrong...
You are not allowed to have default values in the definition of the function. Default values are allowed only in the declaration. Use:
Rachunek::Rachunek(string & name, string & nr, double s) :
surname(name),
nr_account(nr),
balance(s)
{
}
I suggest changing the implementation of the other constructor to initialize the member variables using initializer list syntax.
Rachunek::Rachunek() :
surname("not specified"),
nr_account("0000-0000-0000-0000"),
balance(0.0)
{
}
If you are able to use a C++11 compiler that can be further simplified by using a delegating constructor.
Rachunek::Rachunek() : Rachunek("not specified", "0000-0000-0000-0000", 0.0)
{
}

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

Compiler does't recognize overloaded method in another method

I have two classes: "Station" which has method getName() returning string and "Profit" which has the overloaded method sellAt(string stName), sellAt(Station st). To avoid duplicate code I call sellAt(string stName) in sellAt(string stName), however in some cases (see code example below) compiler gives an error: "no instance of overloaded function "Profit::SellAt" matches the argument list. Argument types are: (std::string)". Is it a bug or I miss something?
Station.h
#pragma once
#include <string>
using namespace std;
class Station
{
private:
string sName;
public:
Station(string name);
string getName();
};
Station.cpp
#include "Station.h"
Station::Station(string name)
:sName(name)
{}
string Station::getName()
{
return sName;
}
Profit.h
#pragma once
#include "Station.h"
#include <string>
class Profit
{
public:
double SellAt(string& stName);
double SellAt(Station& st);
};
Profit.cpp
#include "Profit.h"
double Profit::SellAt(const string& stName)
{
// do stuff
}
// Works as expected
double Profit::SellAt(Station& st)
{
string stName = st.getName();
return SellAt(stName);
}
// Compile error
double Profit::SellAt(Station& st)
{
return SellAt(st.getName());
}
// Compile error
double Profit::SellAt(Station& st)
{
double result = SellAt(st.getName());
return result;
}
Yksisarvinen answered in the comment below the original question:
st.getName() is a temporary. You cannot bind non-const reference to a temporary. I suppose you shouldn't want to modify stName in Profit::SellAt(), so change the type of argument to const std::string&.
Thanks for the help!

Initialize a vector of objects in C++ [duplicate]

This question already has an answer here:
Bizarre issue when populating a list with objects in C++?
(1 answer)
Closed 4 years ago.
my problem is the following: I have a class named City with the paramters Name, Latitude and Longitude. In my main class I want to initialize a vector with some cities.
Here is my City Header File:
using namespace std;
#define RADIUS 6378.137
#define PI 3.14159265358979323846
class City {
public:
City(string _name, double _latitude, double _longitude) {
name = _name;
longitude = _longitude * PI / 180.0;
latitude = _latitude * PI / 180.0;
}
~City() { };
private:
double longitude;
double latitude;
string name;
double earthRadius = RADIUS;
};
And then there is my main class file:
#include <iostream>
#include <vector>
#include "Route.h"
using namespace std;
vector<City> initRoute { (("Boston", 42.3601, -71.0589),
("Houston", 29.7604, -95.3698), ("Austin", 30.2672, -97.7431),
("San Francisco", 37.7749, -122.4194), ("Denver", 39.7392, -104.9903),
("Los Angeles", 34.0522, -118.2437), ("Chicago", 41.8781, -87.6298)) };
int main() {
//for each(City city in initRoute)
//city.printCity;
system("pause");
return 0;
}
When I try to compile it puts out the Error C2398:
Error C2398 Element "1": Die Conversion from "double" to "unsigned int"
requires a restrictive conversion.
I have the feeling that my initialization of my vector is wrong but I dont know what to change.
Thanks for your help :)
You have to specify the type of the object when you're adding it to the vector.
i.e.
vector<City> initRoute { City("Boston", 42.3601, -71.0589),
City("Houston", 29.7604, -95.3698), ... };
Or
You can use the {} to represent the object without explicitly mentioning the class since your vector is holding City objects (just like you do with structs).
i.e.
vector<City> initRoute { {"Boston", 42.3601, -71.0589},
{"Houston", 29.7604, -95.3698}, ... };

C++ Why didn't the default copy work? [duplicate]

This question already has answers here:
Why does the C++ map type argument require an empty constructor when using []?
(6 answers)
Closed 5 years ago.
I've done a lot of Googling and can't seem to figure out what's going on. I'm teaching myself C++ (I'm more familiar with Java).
I have Item Class objects that are being stored in an Inventory Class map, not as pointers. I want to retrieve one of the items from the Inventory in a function, assign it to a temp variable while I delete it from the Inventory map, and then return the object itself so something else can use it. When I originally tried using the code within my function it was returning the error (followed by the stack trace of c++ library stuff):
no matching constructor for initialization of 'Item'
::new ((void*)__p) _Tp();
I tried creating a copy constructor, but to no avail. Eventually, it worked by including an empty constructor ( Item(); ) in my header file and defining it in my cpp file ( Item::Item() {} ).
I would just like to understand why this was necessary so I can recognize it in the future to know what I'm doing.
EDIT: Upon further inspection of the error stack trace, it turned out the actual problem with with the Inventory::addItem function. When assigning an object to a map using operator[], the map first instantiates the value type to the key using the default constructor before making the assignment. No default constructor was available, so the error was returned.
It was fixed by changing the line to map.insert({key, value})
Here are the important parts of the two class files:
//item.h
#include <string>
using namespace std;
class Item {
private:
string name;
int type;
int levelReq;
public:
Item(string name, int type, int levelReq);
Item();
string getName() {return name;}
int getType() {return type;}
friend ostream &operator<<(ostream &out, const Item &item);
};
---------------------------------------------------------------
//item.cpp
#include <string>
#include "item.h"
using namespace std;
Item::Item(string n, int t, int l) : name(n), type(t), levelReq(l) {}
Item::Item() {}
ostream &operator<<(ostream &out, const Item &item) {
return out << item.name;
}
---------------------------------------------------------------
//inventory.h
#include <map>
#include "item.h"
class Inventory {
private:
map <int, Item> inventory;
int size;
bool full;
int nextFree;
void findNextFree();
public:
Inventory();
bool isFull() {return full;}
void addItem(Item item);
Item getItem(int slot);
void showInv();
};
---------------------------------------------------------------
//inventory.cpp
#include <iostream>
#include <string>
#include "inventory.h"
#include "item.h"
using namespace std;
Inventory::Inventory() {
full = false;
nextFree = 1;
size = 28;
}
void Inventory::addItem(Item item) {
if (!full) {
inventory[nextFree] = item;
findNextFree();
}
else {
cout << "Your inventory is full (Inv::addItem)";
}
}
Item Inventory::getItem(int slot) {
Item item = inventory.at(slot);
inventory.erase(slot);
full = false;
if (nextFree > slot) {
nextFree = slot;
}
return item;
}
void Inventory::findNextFree() {
nextFree++;
if (nextFree == size + 1) {
full = true;
}
else if (inventory.count(nextFree)) {
findNextFree();
}
}
I think the issue rose because you declared a constructor for your item class.
C++ will automatically generate the necessary constructors if you don't provide any custom constructors.
The necessary constructors are the default, copy and move constructors.
The moment you provide one, the default constructors won't be generated and you have this issue. This principle will also apply to structs.
Check the reference to see for yourself:
http://en.cppreference.com/w/cpp/language/default_constructor
http://en.cppreference.com/w/cpp/language/copy_constructor
http://en.cppreference.com/w/cpp/language/move_constructor
Hope this answers your question.

Unidentified reference to constructor (c++) [duplicate]

This question already has answers here:
Undefined reference C++
(2 answers)
Closed 9 years ago.
I have done some research and googling on this error for days, as far as I know this is a common problem for many in c++, I still haven't found a clear answer to this error. I've read that linking the files can fix this, but I could find any example codes to do this. I'am so close to finishing this code, all I need to do to call the constructor from the main file (or just make a simple object), but I keep getting this "unidentified reference to NamedStorm::NamedStorm()" error, please help.
MAIN.CPP
#include <iostream>
#include <string>
#include "NamedStorm.h"
using namespace std;
NamedStorm storm[2];
int main(){
// NamedStorm Chris("Chris", 70.0, "T.S.", 990.0);
// storm[0] = Chris;
return 0;
}
NamedStorm.cpp
// CPP => Function definition
#include <string>
#include "NamedStorm.h"
using namespace std;
// Defining static variables
int NamedStorm::stormCount = 0;
// Constructor definition
NamedStorm::NamedStorm(std::string sName, double wSpeed, std::string sCat, double sPress){
stormName = sName;
windSpeed = wSpeed;
stormCategory = sCat;
stormPressure = sPress;
stormCount++;
}
NamedStorm::NamedStorm(std::string sName){
stormName = sName;
stormCount++;
}
NamedStorm::NamedStorm(){
stormName = sName;
stormCount++;
}
// Destructor definition
//NamedStorm::~NamedStorm(){}
// Get (Accessor) function definition
int NamedStorm::getStormCount(){
return stormCount;
}
double NamedStorm::getStormPressure(){
return stormPressure;
}
string NamedStorm::getStormCategory(){
return stormCategory;
}
string NamedStorm::getName(){
return stormName;
}
// Set (Mutator) function definition
void NamedStorm::displayOutput(){}
void NamedStorm::sortByNames(){}
void NamedStorm::getAverageStormPressure(){}
void NamedStorm::getAverageWindSpeed(){}
void NamedStorm::getWindSpeed(){}
NamedStorm.h
#ifndef NAMEDSTORM_H_INCLUDED
#define NAMEDSTORM_H_INCLUDED
// NEVER use using namespce in header, use std instead.
class NamedStorm{
private:
std::string stormName;
std::string stormCategory;
double maxWindSpeed;
double stormPressure;
static int stormCount;
public:
// Constructor
NamedStorm(std::string, double, std::string, double);
NamedStorm(std::string);
NamedStorm();
// Destructor
//~NamedStorm();
// Get functions
int getStormCount();
double getStormPressure();
double getWindSpeed();
std::string getStormCategory();
std::string getName();
// Set functions
static void displayOutput();
static void sortByNames();
static void sortByWindSpeed();
static void getAverageWindSpeed();
static void getAverageStormPressure();
};
#endif // NAMEDSTORM_H_INCLUDED
Why is the definition of the default constructor the same as of the NamedStorm::NamedStorm(std::string) ? I would start from correcting that.