Getter seems to crash the program even with 0 errors - c++

im new in the C++ world and coding in general, just started studying getters and setters and made areally simple exercise to practice them, the build seems to have 0 errors and 2 minor warnings, however, when I try to use a function to return a private variable and print it, it simply crashes the program, however, if i use the last function I made "getAccount()" It seems to work just fine.
After some poking, it seems like the problem is with the getter functions, just calling them crashes the program, here's the code:
main.cpp
#include <iostream>
#include "Person.h"
using namespace std;
int main()
{
User user;
user.setUser("someuser");
user.setPassw("somepassword");
cout << user.getPassw() << endl;
cout << user.getUser() << endl;
user.getAccount();
}
Person.h
#define PERSON_H
#include <iostream>
using namespace std;
class User
{
private:
string username;
string password;
public:
string setUser(string usernm);
string setPassw(string pass);
string getUser();
string getPassw();
void getAccount();
};
#endif // PERSON_H
Person.cpp
#include <iostream>
#include "Person.h"
using namespace std;
string User::setUser(string usernm){
usernm = username;
}
string User::setPassw(string pass){
pass = password;
}
string User::getUser(){
return username;
}
string User::getPassw(){
return password;
}
void User::getAccount(){
cout << "Account is:" << endl;
cout << "Username: " + username << endl;
cout << "Password: " + password << endl;
}

Not all functions declared to return values actually return values so you have Undefined Behaviour and anything could happen.
Example:
string User::setUser(string usernm){
usernm = username;
// should return a string here
}
string User::setPassw(string pass){
pass = password;
// should return a string here
}
Apart from that, you assign usernm and pass when you should assign username and password so the set operations does not set the member variables.

Related

My getlines are showing an error as well as my get functions when I put in a variable in the parentheses c++

I have a banking project and I am trying to set up the bank name, address, and working hours. My getlines are showing an error as well as my get functions.
Input exact error messages here please.
'getline': no matching overloaded function found
no suitable user-defined conversion from "Bank" to "std::string" exists
Here's the class for bank:
#include <iostream>
#include <string>
#include <vector>
#include <ctime>
#include <cctype>
#include <cstdlib>
using namespace std;
class Bank {
public:
void setBankName(string bn) { bn = bankname; }
string getBankName() { return bankname; }
void setBankAdd(string ba) { ba = bankadd; }
string getBankAdd() { return bankadd; }
void setWorkingHours(string bwh) { bwh = bankworkinghours; };
string getWorkingHours() { return bankworkinghours; }
private:
string bankname, bankadd, bankworkinghours;
};
//and then this is in my main function
int main() {
Bank bankname, bankadd, bankworkinghours;
char userChoice; // numbers 1-9
int number=0;
system ("color 5f");
cout << "Name of bank: ";
getline(cin, bankname); **//all the get lines also show error**
cout << endl;
cout << "Bank address: ";
getline(cin, bankadd);
cout << endl;
cout << "Bank working hours: ";
getline(cin, bankworkinghours);
cout << endl;
bankname.setBankName(bankname); //the things in the parentheses show error
bankadd.setBankAdd(bankadd);
bankworkinghours.setWorkingHours(bankworkinghours);
The error is self explanatory. 2nd parameter of getline function is std:string so define bankname as std:string and then set the name of bank object by setBankName.
1- You did not created bank Object in the main to set class attributes.
You need an Object with reference to that object you will set the parameters of the class bank.
2- bankname, bankadd, bankworkinghours are string and you made them Bank
Here is updated code and working fine in VS 2019 without any error. Just a few changes in the first 2 and last three lines of main
#include <iostream>
#include <string>
#include <vector>
#include <ctime>
#include <cctype>
#include <cstdlib>
using namespace std;
class Bank {
public:
void setBankName(string bn) { bn = bankname; }
string getBankName() { return bankname; }
void setBankAdd(string ba) { ba = bankadd; }
string getBankAdd() { return bankadd; }
void setWorkingHours(string bwh) { bwh = bankworkinghours; };
string getWorkingHours() { return bankworkinghours; }
private:
string bankname, bankadd, bankworkinghours;
};
//and then this is in my main function
int main() {
Bank bankObj;
string bankname, bankadd, bankworkinghours;
char userChoice; // numbers 1-9
int number = 0;
system("color 5f");
cout << "Name of bank: ";
getline(cin, bankname);
cout << endl;
cout << "Bank address: ";
getline(cin, bankadd);
cout << endl;
cout << "Bank working hours: ";
getline(cin, bankworkinghours);
cout << endl;
bankObj.setBankName(bankname);
bankObj.setBankAdd(bankadd);
bankObj.setWorkingHours(bankworkinghours);
}
void setBankName(string bn) { bn = bankname; } is the wrong way around. try bankname = bn.

Calling a string getter function from a header file

I'm learning C++, and I'm just messing around with putting classes in separate files for practice. I have a getter function, which returns a string (because the variable is saved as a string). However, from my main() function, I am not sure how to call it. I know the problem is probably that I need to include string somewhere when I call the object, but I have no idea how to format it.
I know this is a pretty newbie questions, but I couldn't find the answer anywhere. Could someone help me out?
(p.s. I'm not trying to get this specific code to work, since it's useless. I'm just trying to learn how to apply it for future reference).
I've tried throwing in string in a couple of places when calling or creating the object, but I always get an error. I know I could get around it by not encapsulating the variable or not having a separate class file, but that's not what I want.
main.cpp
#include <iostream>
#include "usernameclass.h"
#include <string>
using namespace std;
int main()
{
usernameclass usernameobject;
usernameobject.getUsername();
return 0;
}
usernameclass.h
#ifndef USERNAMECLASS_H
#define USERNAMECLASS_H
#include <string>
class usernameclass
{
public:
usernameclass();
std::string getUsername();
void setUsername(std::string name);
askUsername();
private:
std::string usernameVar = "test";
};
#endif
usernameclass.cpp
#include "usernameclass.h"
#include <iostream>
#include "username.h"
#include <string>
using namespace std;
string usernameclass::getUsername(){
return usernameVar;
cout << "test cout" << endl;
}
usernameclass::askUsername(){
string name;
cout << "What is your name?" << endl;
cin >> name;
setUsername(name);
cout << "Ah, so your name is "+usernameVar+", great name I guess!" << endl;
cin.get();
cin.get();
cout << "You're about to do some stuff, so get ready!" << endl;
}
usernameclass::usernameclass(){}
void usernameclass::setUsername(string name){
string* nameptr = &usernameVar;
*nameptr = name;
}
Expected result: runs getUsername() function and returns usernameVar
Actual result: doesn't run the getUsername() function
The current code would not compile, because you have not specified return type of 'askUsername()' routine, which is 'void', I believe.
Other things are good, apart from an output in 'getUsername()', which happens after returning from the function and about which you should have received a warning, I guess.
To the question: you can call that 'get' method in 'main()' as:
cout << usernameobject.getUsername();
Your code should be structured more like this instead:
main.cpp
#include <iostream>
#include "usernameclass.h"
int main()
{
usernameclass usernameobject;
// optional:
// usernameobject.askUsername();
// do something with usernameobject.getUsername() as needed...
return 0;
}
usernameclass.h
#ifndef USERNAMECLASS_H
#define USERNAMECLASS_H
#include <string>
class usernameclass
{
public:
std::string getUsername() const;
void setUsername(std::string name);
void askUsername();
private:
std::string usernameVar = "test";
};
#endif
usernameclass.cpp
#include <iostream>
#include "usernameclass.h"
std::string usernameclass::getUsername() const {
return usernameVar;
}
void usernameclass::setUsername(std::string name) {
usernameVar = name;
}
void usernameclass::askUsername() {
std::string name;
std::cout << "What is your name?" << std::endl;
std::getline(std::cin, std::name);
setUsername(name);
std::cout << "Ah, so your name is " << getUsername() << ", great name I guess!" << std::endl;
std::cout << "You're about to do some stuff, so get ready!" << std::endl;
}

dynamic object creation in c++?

If my class name is TEST i want to create an object of TEST class having name given by the user during run time??
i tried this-
#include<iostream>
#include<string.h>
#include<conio.h>
using namespace std;
class TEST
{
void end()
{
cout<<"Hi";
}
};
int main()
{
string name;
cout<<"Give a object name";
cin>>name;//taking name from user
TEST name;//here i am getting error while creating object of TEST class
return 0;
}
It's not clear exactly what you are trying to do here, except perhaps learning basic c++ constructs. Here is some code to get you going.
#include <iostream>
#include <string>
#include <map>
using namespace std;
class TEST
{
public:
//Constructor - sets member string to input
TEST( string input ) : _name( input )
{
}
//Destructor called when object goes out of scope
~TEST()
{
cout << "Hi from destructor" << endl;
}
//Variable stored by the class
string _name;
};
int main()
{
string inputString;
cout << "Give a object name";
cin >> inputString;
// Give name to your class instance through the constructor
TEST foo( inputString );
// Store a copy of the object "foo" in a map that can be referenced by name
map< string, TEST > userNamedObjects;
userNamedObjects.insert( { inputString, foo } );
// Access the object's data based on user input name
cout << "From map: " << userNamedObjects.at( inputString )._name << endl;
// Sanity check
cout << foo._name << endl;
// Or set it directly
foo._name = "Patrick Swayze";
cout << foo._name << endl;
// The stored object doesn't change, because it's a copy
cout << "From map: " << userNamedObjects.at( inputString )._name << endl;
return 0;
}

How do I use the same string in 2 code blocks?

just start C++ through a series of youtube tutorials, I tried to look online but I did not know what vocabulary to use to explain my problem. I was testing pointers and I made this file which basically gets a username from the user and says it again but I don't know how reuse the username in another codeblock.
// Testing Pointerds.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
// This program just takes someones username and says it again.
// I get the name in void intro(), but how do I use the same string in another code block function?
// If I need to use it in 'void reuse()' how do I use the same name they type in in 'void intro()'?
void start()
{
cout << "What would you like to be called?"<<endl;
}
void usernameGet(string *a)
{
getline(cin,*a);
}
void intro()
{
string username;
start();
usernameGet(&username);
cout << "Welcome " << username << endl; // it has the username here but I want to use it in the next code block
cin.get();
}
void reuse()
{
// how do I use the same name in intro in this one?
}
int main()
{
intro();
reuse();
}
By passing the variable around, i.e. return it from the place where it's first initialized and pass it as an argument to the next place where it's needed. That way you avoid global state, which is nice.
You have to pass or return the value, something like:
std::string intro()
{
std::string username;
start();
usernameGet(&username);
std::cout << "Welcome " << username << std::endl;
std::cin.get();
return username;
}
void reuse(const std::string& name)
{
// Reuse name
}
int main()
{
std::string username = intro();
reuse(username);
}

How to call a function inside a class

I am trying to call a function inside a class, when I try I get the error "no operator << matches these operands" right before instructor.displayMessage(). Also, am I calling instructor.displayMessage() correctly? I am new to c++
#include <iostream>
#include "GradeBook.h"
using namespace std;
int main()
{
GradeBook gradeBook1("CS101 Introduction to C++ Programming");
GradeBook gradeBook2("CS102 Data Structures in C++");
GradeBook instructor("");
instructor.setInstructorName();
cout << "gradeBook1 created for course: \n" << gradeBook1.getCourseName() << instructor.displayMessage()
<< "\ngradeBook2 created for course: \n" << gradeBook2.getCourseName()
<< endl;
cout << "\nPress any key to exit" << endl;
getchar();
}
Header:
#include <string>
using namespace std;
class GradeBook{
public:
GradeBook(string);
void setCourseName(string);
string getCourseName();
void displayMessage();
void setInstructorName();
string getInstructorName();
private:
string courseName;
string instructorName;
};
I didnt include the functions because I dont think they are part of the problem.
void displayMessage();
This function does not return anything, yet you try to print its return value here:
cout << "gradeBook1 created for course: \n" << gradeBook1.getCourseName() << instructor.displayMessage()
If it actually should return something, then you have to declare it with the correct return type, for example
string displayMessage();
However the name suggests that the function itself prints the output already. So maybe you simply want to call it, like this:
instructor.displayMessage();
in a single line.
If you provide the implementation of displayMessage() I might give a more precise answer.