Error in constructor - C++ - c++

I have just learnt some object oriented programming concepts in Python, but I want to transfer this knowledge to C++, and I have trouble with basic implementation that used to be easy using Python.
#include<iostream>
using namespace std;
class Animal{
char name;
int age;
public:
Animal(char name, int age);
};
Animal::Animal(char name, int age) {
this->name = name;
this->age = age;
}
int main()
{
Animal dog ("Megg", 10);
cout << "Name: " dog.name <<endl;
return 0;
}
When I compile this code, I get a lot of messages, such as:
error: no matching function for call to 'Animal::Animal(const char[5], int)'
note: Animal::Animal(char, int) <near match>
note: candidate expects 1 argument, 2 provided
Thanks!

you don't need to do this->name = name in your constructor definition
"Megg" is a string literal. You can cast "Megg" into const char * but not into a char (this was most likely causing your error).
or better yet. You can use the C++ Standard Library string class std::string
#include <iostream>
#include <string>
class Animal{
std::string name;
int age;
public:
Animal(std::string name, int age);
std::string getName() const;
int getAge() const;
};
Animal::Animal(std::string Name, int Age) {
name = Name;
age = Age;
}
std::string Animal::getName() const {
return name;
}
int Animal::getAge() const {
return age;
}
int main()
{
Animal dog ("Megg", 10);
std::cout << "Name: " << dog.getName() << std::endl; // Error in this line. Missing << between "Name: " and dog.name
return 0;
}
Some additional edits:
You should avoid using using namespace std as it takes everything in the Standard Library (from the files you've included) and puts it in the global namespace. You can instead use the scope resolution operator :: as seen above.
When you start working with multiple libraries you may encounter that both have a class named vector or string, or functions with the same name. The way to avoid this is to specify what namespace you want to use.
or alteratively you can do the following:
using std::cout;
using std::endl;
using std::string;
Additionaly in order for you program to work you need a way to access your object's member variables. You could do this by making the variables public or the better practice is to add accessor functions.

Related

C++ class object default constructor bug

I am trying to create a class object s2 with some customized attributes and some attributes from default constructor however my output is the wrong output for the get_year function. It should be outputing 0 which is the key for FRESHMAN but it is out putting 2 instead. The rest of the code is outputting as expected:
#include <stdio.h>
#include <iostream>
#include <algorithm> // for std::find
#include <iterator> // for std::begin, std::end
#include <ctime>
#include <vector>
#include <cctype>
using namespace std;
enum year {FRESHMAN, SOPHOMORE, JUNIOR, SENIOR};
struct name
{
string firstName;
string lastName;
friend std::ostream& operator <<(ostream& os, const name& input)
{
os << input.firstName << ' ' << input.lastName << '\n';
return os;
}
};
class Student: name{
private:
name Name;
year Year;
int idNumber;
string Department;
public:
void setname(string fn="", string ln="")
{
Name.firstName =fn;
Name.lastName =ln;
}
name get_name()
{
return Name;
}
void set_year(year yr=FRESHMAN)
{
Year=yr;
}
year get_year()
{
return Year;
}
void set_ID(int ID=0)
{
idNumber=ID;
}
int get_ID()
{
return idNumber;
}
void set_Department(string Dept="")
{
Department=Dept;
}
string get_Department()
{
return Department;
}
};
int main()
{
Student s2;
s2.setname("Nikolai", "Khabeboolin");
s2.set_ID(12436193);
cout<<"ID is: "<< s2.get_ID()<<", name is "<< s2.get_name()<<", year in school is: "<<s2.get_year()<<", Department is "<<s2.get_Department()<<endl;
return 0;
}
Student lacks a constructor, so all its members are default initialized, and the default initialization of year Year and int idNumber is "no initialization", so reading from them is undefined behavior. Reading them might find 0, 2, a random value each time, or crash.
I see that your class contains a void set_year(year yr=FRESHMAN) member, but your code never called set_year, so no part of this executed.
You should make a default constructor for Student, or as Goswin von Brederlow stated, use year Year{FRESHMAN}; and int idNumber{-1}; when declaring the members, to give them default initializations.
By not explicitly declaring and defining a constructor, in this case Student(), you open yourself up to undefined behavior. Your constructor should call set_year(year yr=FRESHMAN) OR even better, just set the year itself.

not " using namespace std; " gives me an unexpected error (C++)

This Is my first post here. I have a question about "using namespace std;". I hope I'm posting this right, but please do tell me If I did something wrong!
**Problem: ** So the problem that occurs Is that when I remove 'using namespace std;' I get an unexpected error which gives me the following error: "identifier 'to_string' is undefined". So my question Is, why Is it that I get this unexpected error. (I have marked below with "<-- this part here") where the error occurs once I remove 'using namespace std;' ". Seems a bit weird to me that I'd have to declare "to_strong" beforehand, but when using namespace std; It somehow declares It for me?
#include <iostream>
#include <string>
using namespace std;
// class name {}
class Person
{
private:
std::string name;
int age;
public:
Person()
{
std::cout << "Constructor called!" << "\n";
// (this) signals we are trying to access the veriables of private
this->name = "N/A";
this->age = 0;
}
~Person() // Destructor is a member function which destructs or deletes an object.
{
std::cout << "Destrouctor called!" << "\n";
}
// Accessors (Getters)
const std::string& getName() const { return this->name; }
const int& getAge() const { return this->age; }
// Modifiers (Setters)
void setName(const std::string name) { this->name = name; }
void setAge(const int age) { this->age = age; }
// Functions
const std::string toString() const
{
return "Name: " + this->name + " Age: " + to_string(this->age); <-- This part here
}
};
you need to use
std::to_string()
std:: means standard namespace

Expression must have class type. Don't know how to solve

I'm new to the cpp language and I have a problem with my code which I don't know how to solve, I looked here on some other questions people asked about this error, but none of the answers really helped me to solve the problem.
So this is my main function:
#include <iostream>
#include "Person.h"
#include <string>
int main() {
Person p2();
Person p1();
std::cout << p1.toString() << std::endl;
return 0;
}
and here is my Person.h file:
#ifndef PERSON_H_
#define PERSON_H_
#include <string>
class Person {
private:
int age;
std::string name;
int numOfKids;
public:
Person() {
this->age = 0;
this->name = "bob";
this->numOfKids = 5;
}
Person(int agee, std::string namee, int numof);
~Person();
std::string toString();
};
#endif // PERSON_H_
In the main function it marks p1.toString() and says "expression must have class type"
and I don't know what to do, I tried many things and none of them worked.
These kind of statement you write can have ambigous meaning:
Person p2();
(what you want) a variable p2 with type Person and default constructed.
(the compiler thought) a function declaration p2 returning an object of Persion.
Remove the bracket or using the '{}' (c++11) should make things clear:
Person p1{};
Person p2;
Various points to correct:
Person(int agee, std::string namee, int numof);
~Person();
std::string toString();
These three are only declared, not defined. This will result in unresolved external symbol error messages from the compiler.
Correct also the the variable declarations of p1 and p2.
Use this snip as an orientation:
#include <iostream>
class Person
{
private:
int age;
std::string name;
int numOfKids;
public:
Person()
{
this->age = 0;
this->name = "bob";
this->numOfKids = 5;
}
Person(int agee, std::string namee, int numof)
{
// ToDo
}
~Person()
{
// ToDo
}
std::string toString()
{
// ToDo
return "";
}
};
int main()
{
Person p2;
Person p1;
std::cout << p1.toString() << std::endl;
return 0;
}

Issue with using string data type for a class property in C++

I'm currently defining a few properties for a class in C++ but I'm running into trouble when using type string as opposed to something like int or double. For example:
private:
int LOT;
public:
int getLOT() {
return LOT;
}
void setLOT(int value) {
LOT = value;
}
works fine, but:
private:
string name;
public:
string getName() {
return name;
}
void setName(string value) {
name = value;
}
throws these errors:
https://s26.postimg.org/wm5y7922h/error.png
The file (a header) looks something like this:
#include "general.h" // a header which includes all my other #includes
// which, yes, does include <string>
class MyClass
{
private:
string name;
public:
string getName() {
return name;
}
void setName(string value) {
name = value;
}
// other properties similar to the above
}
The purpose is to access the variable like this:
cout << "Enter your name: ";
cin >> MyClass.setName();
cout << "\nHello, " << MyClass.getName();
// although this isn't exactly how it'll be used in-program
If anyone could provide help with what I'm doing wrong or a better way to go about a string property (as, like I mentioned before, other types work fine) it would be greatly appreciated. Thanks.
string is part of std namespace.
You must use std::string instead of string or add using namespace std; (what I would not recommend you to do in your header file, read "using namespace" in c++ headers).

error: incompatible types in assignment of ‘char’ to ‘char [11]’

I'm trying to create a member function that allows an user to set member array variables.
I've been looking everywhere but I can't find the problem in my code,
#include <string>
#include <iostream>
using namespace std;
class Employee
{
protected:
string name;
char ssn[11];
char id[5];
char hired[8];
public:
Employee(char ssn, char id, char hired); //Constructor
Employee(string name);
~Employee(); //Destructor
void setName(string n) { n = name; }
void setSSN(char i) { ssn = i; }
};
int main()
{
return 0;
}
Let's have a look at your setSSN function:
void setSSN(char i) { ssn = i; }
SNN, which most likely means social security number, doesn't consist of just one digit but 11, right? Then why would setSSN take as input only one character (digit) by (char i)? So setSSN function should rather take a string of characters containing SSN of the employee and that string should be of the same flavor as the ssn member variable of your Employee class in order to let you assign one string variable by another in the body of setSSN function. If you are already familiar with the string class of the C++ standard library, you should probably use that class for all your string storage and manipulation.